Fluent HTTP request client
Use go get:
$ go get github.com/m90/rekwestPerform a POST request, encoding the JSON response into data, by calling Do(targets ...interface{}) on the previously constructed request:
req := rekwest.New("https://www.example.com/api/create-animal").
Method(http.MethodPost).
JSONBody(map[string]interface{}{
"kind": "platypus",
"flappers": true,
}).
BasicAuth("username", "secret")
data := responseType{}
if err := req.Do(&data); err != nil {
panic(err)
}Use BasicAuth(username, password string) or BearerToken(token string) to send Authorization headers:
rekwest.New("https://www.example.com/api").BasicAuth("user", "pass")
rekwest.New("https://www.example.com/api").BearerToken("my-token")Add a context.Context using Context(ctx context.Context):
timeout, cancel := context.WithTimeout(context.Background(), time.Minute)
defer cancel()
rekwest.New("https://www.example.com/api").Context(timeout).Do()Set a duration for when the request is supposed to time out using Timeout(value time.Duration):
rekwest.New("https://www.example.com/api").Timeout(time.Second)Set header values using Header(key, value string) or Headers(headers map[string]string):
r := rekwest.New("https://www.example.com/api").Header("X-Foo", "bar")
r.Headers(map[string]string{
"X-Bar": "foo",
"X-Other": "another one",
})Use a custom http.Client instance by passing it to Client(client *http.Client):
rekwest.New("https://www.example.com/api").Client(&http.Client{
Timeout: time.Second,
})Use ResponseFormat(format ResponseFormat) in case you want to specify the expected payload:
json := rekwest.New("https://www.example.com/api").ResponseFormat(rekwest.ResponseFormatJSON)
data := responseType{}
err := json.Do(&data)Available formats are ResponseFormatJSON, ResponseFormatXML and ResponseFormatBytes. If no value is set, rekwest will try to read the responses Content-Type header and act accordingly. If none is sent, the response body will be treated as type []byte.
For JSON and XML, the correct Accept header will be automatically set.
Request payloads can automatically be marshalled into the desired format using JSONBody(data interface{}), XMLBody(data interface{}) and MarshalBody(data interface{}, marshalFunc func(interface{}) ([]byte, error)):
rekwest.New("https://www.example.com/api/create-animal").
Method(http.MethodPost).
JSONBody(map[string]interface{}{
"kind": "platypus",
"flappers": true,
})Alternatively an io.Reader can be passed to Body(data io.Reader).
MIT © Frederik Ring