[Go] Change query parameters to use `go-querystring` from `map[string]interface{}`
Description / Suggest an enhancement
Version 2.3.0 made a huge improvement for query string parameters by moving to a map[string]interface{} from a sequence of function parameters. Moving further to a query string parameter struct using Google's go-querystring (https://github.com/google/go-querystring) seems like it would be a nice enhancement.
Note: I still need to try out 3.0.0 to see if this is there already. I noticed it doesn't use the -c flag any more so need to look into this more.
Thanks for the suggestion, I am not happy using the map[string]interface{} but it appeared like the best solution at the time.
I did look at using a similar interface to go-querystring so the feel is more standard to go, but the issue is when parameters are not passed; for example:
opt := Options{ "foo" }
v, _ := query.Values(opt)
fmt.Print(v.Encode()) // will output: "q=foo&all=false&page=0"
Because the int was not specified, it defaults to 0; there is no page 0. This may seem quite simple to work around, but other API's could have many more optional arguments such as:
@param optional (nil or map[string]interface{}) with one or more of:
@param "datasource" (string) The server name you would like data from
@param "labels" ([]int64) Fetch only mails that match one or more of the given labels
@param "lastMailId" (int32) List only mail with an ID lower than the given ID, if present
@param "token" (string) Access token to use if unable to set a header
@param "userAgent" (string) Client identifier, takes precedence over headers
@param "xUserAgent" (string) Client identifier, takes precedence over User-Agent
In the above set:
- You have to call without
lastMailIdto find what that lowest ID would be, 0 would return nothing. - If a blank
labelsis passed nothing is returned. - Setting
userAgentto a blank string will mean the API provider cannot tell who you are (and result in a ban).
I am still looking at options here, if you have an idea how to solve this, let me know.
You can use omitempty option to exclude unused parameters.
type Options struct {
Query *string `url:"q"`
ShowAll *bool `url:"all,omitempty"`
Page *int `url:"page,omitempty"`
Limit int `url:"limit,omitempty"`
}
func main() {
q := "foo"
p := 0
opt := Options{Query: &q, Page: &p, Limit: 0}
v, _ := query.Values(opt)
fmt.Print(v.Encode()) // => page=0&q=foo
}
It should be noted that value fields (not pointer) annotated with omitempty are also excluded when zero value is set (e.g., Limit.) so, omitempty fields are desirable to be a pointer.