Original post

I am writing a module for a public API and a large part of that API is using query parameters to get the data you want.

Currently I have something that looks a bit like this:

type Query struct {
        Name    string
        MaxSize int
        Forward bool
        // carries on for 20 or so parameters
}

func (q Query) Request() *http.Request {
        req, _ := http.NewRequest("GET", "https://api.example.com", nil)
        params := req.URL.Query()

        if q.Name != "" {
                params.Add("name", q.Name)
        }
        if q.MaxSize != 0 {
                params.Add("maxSize", strconv.Itoa(q.MaxSize))
        }
        if q.Forward != false {
                params.Add("forward", strconv.FormatBool(q.Forward))
        }
        // etc...

        req.URL.RawQuery = params.Encode()
        return req
}

Obviously with such a large amount of parameters, the list of if statements and Add calls gets a bit long.

I also have a similar structure for adding headers to the request, so with multiple query types with different headers I end up with hundreds of lines of if,Add, and Set

Is this the best way of doing something like this? I thought about using mapstructure to convert it to a map but even then I would need to check for zero values.