英文:
go generate with gofmt, replacing variable value
问题
发布了'generate'工具,为许多令人兴奋的可能性打开了大门。
我一直在努力改进我的测试。我有一个函数,它查询一个外部API,该API的位置在全局变量中定义。其中一个问题是将该值替换为在“生成时间”确定的值。
我有:
//go:generate gofmt -w -r "var apiUrl = a -> var apiUrl = \"http://example.com\"" $GOFILE
运行go generate然后出现错误:
parsing pattern var apiUrl = a at 1:1: expected operand, found 'var'
不能使用占位符,如下所示:
gofmt -r 'API_GOES_HERE -> "http://example.com"' -w
因为当我编译生产代码时,源代码会被重写,所以后续的测试编译无法再替换占位符(它已经被替换了)。
我意识到我有点滥用gofmt
,但我宁愿不回到sed
。
什么是有效的go:generate
语句?
英文:
The release of the 'generate' tool opens up a whole lot of exciting possibilities.
I've been trying to make my tests better. I have a function which queries an external API, the location of that API is defined in a global variable. One piece of the puzzle is replacing that value with a value determined at 'generate time'.
I have:
//go:generate gofmt -w -r "var apiUrl = a -> var apiUrl = \"http://example.com\"" $GOFILE
Running go generate then errors out with:
parsing pattern var apiUrl = a at 1:1: expected operand, found 'var'
It's not an option to use a place holder like so:
gofmt -r 'API_GOES_HERE -> "http://example.com"' -w
That's because, when I compile production code, the source gets rewritten, so subsequent compiles for testing no longer can replace the place holder (it has been replaced already).
I realise I'm abusing gofmt
somewhat but I'd rather not go back to sed
.
What would be the valid go:generate
statement?
答案1
得分: 3
你可以使用链接器标志-X
来实现。例如,
go build -ldflags "-X main.APIURL 'http://example.com'"
将使用APIURL
变量设置为http://example.com
来构建你的程序。
**Go 1.5编辑:**从Go 1.5开始,建议使用新的格式:
go build -ldflags "-X main.APIURL=http://example.com"
(注意等号)。
英文:
You can use a linker flag -X
for that. For example,
go build -ldflags "-X main.APIURL 'http://example.com'"
will build your program with APIURL
variable set to http://example.com
.
Go 1.5 edit: starting with Go 1.5, it's recommended to use the new format:
go build -ldflags "-X main.APIURL=http://example.com"
(Note the equals sign.)
答案2
得分: 1
在你的测试文件api_test.go
中,添加一个生成命令,生成另一个名为api_endpoint_test.go
的文件,该文件位于同一个包中,并且只定义或初始化(使用init
函数)你所需的变量。该变量的值仅在测试期间使用。
值得一提的是,我不太明白为什么你要这样做,而不是在运行时初始化变量或使用一些常规的配置方法。
英文:
In your test file say api_test.go
add a generate command that produces another file called api_endpoint_test.go
that is in the same package and only defines or inits ( using an init
function ) the variable you need. That variable value will only be used during testing.
For the record, I don't quite know understand why you are trying to do it this way, instead of either initiatializing the variable during runtime or using some conventional configuration method.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论