Go generate with gofmt, replacing the value of the variable

The release of the 'generate' tool opens up many interesting possibilities. I tried to improve my tests. I have a function that requests an external API, the location of this API is defined in a global variable. One piece of the puzzle replaces this value with the value defined in "time generation".

I have:

//go:generate gofmt -w -r "var apiUrl = a -> var apiUrl = \"http://example.com\"" $GOFILE

Running go will then generate errors using:

parsing pattern var apiUrl = a  at 1:1: expected operand, found 'var'

It is not possible to use a seat holder like this:

gofmt -r 'API_GOES_HERE -> "http://example.com"' -w

This is because when I compile the production code, the source is overwritten, so subsequent compilations for testing can no longer replace the place holder (it has already been replaced).

, gofmt, sed. go:generate?

+4
2

-X. ,

go build -ldflags "-X main.APIURL 'http://example.com'"

APIURL, http://example.com.

.


Go 1.5 edit:, Go 1.5, :

go build -ldflags "-X main.APIURL=http://example.com"

( .)

+3

api_test.go , api_endpoint_test.go, , inits ( init) . .


, , , - .

+1

All Articles