Query parameters
Add query parameters individually, from a map, or as repeated values.
apitest.Handler(handler).
Get("/hello").
QueryParams(map[string]string{"a": "1", "b": "2"}).
Query("c", "d").
QueryCollection(map[string][]string{"e": {"f", "g"}}).
Expect(t).
Status(http.StatusOK).
End()The request in this example is sent to /hello?a=1&b=2&c=d&e=f&e=g.
| Method | Behaviour |
|---|---|
Query(key, value) | Adds a value for the key. Call it again with the same key to repeat the parameter. |
QueryParams(map[string]string) | Adds a value for each entry in the map. |
QueryCollection(map[string][]string) | Sets repeated parameters, so {"e": {"f", "g"}} becomes e=f&e=g. Calling it again replaces the earlier collection. |
All three can be combined in one request.
Encoding
Parameters added with the builder methods are encoded with Go's url.Values, which escapes values and sorts the keys. The order you add them in therefore does not change the URL, which keeps tests stable. A query string written into the URL is sent unchanged.
If the handler expects an encoding url.Values cannot produce, such as PHP style ids[]=1&ids[]=2, set the raw query with an interceptor:
apitest.Handler(handler).
Intercept(func(req *http.Request) {
req.URL.RawQuery = "ids[]=1&ids[]=2"
}).
Get("/users").
Expect(t).
Status(http.StatusOK).
End()Query parameters in the URL
A query string can also be written into the URL. It is sent as written, and parameters from the builder methods are appended after it, so this request is sent to /articles?page=2&sort=asc:
apitest.Handler(handler).
Get("/articles?page=2").
Query("sort", "asc").
Expect(t).
Status(http.StatusOK).
End()Before v1.7.0
Earlier versions discarded a query string written into the URL. On those versions, add every parameter with the builder methods.