Request / Response
This package comes with a chainable request builder and response wrapper.
Usage:
go
// You can use httpx.Request to build a new request
// and chain request building methods.
req := httpx.Request("GET", "http://example.com").
Query("foo", "bar"). // or QueryMap, QueryMapFmt, QueryValues, QueryStruct
Header("X-Foo", "Bar"). // or HeaderMap, HeaderMapFmt, HeaderValues
BodyJson(map[string]any{"foo": "bar"}) // or Body, BodyText, BodyForm
// We have multiple ways to finalize request building.
res := req.Build() // Build resulting *http.Request
res := req.Do() // Execute request and get *ResponseWrapper
res := req.Async() // Execute request asynchronously and get *async.Future[*ResponseWrapper]
// You can use httpx.Response to wrap existing *http.Response with error.
res := httpx.Response(http.DefaultClient.Get("http://example.com"))
// ResponseWrapper provides a few useful methods to operate with response.
// It's chainable, so you can use it in a fluent way.
// If error occurs on any stage,
// following methods will not be executed.
// Error will be stored in ResponseWrapper
// and you can get it with an Error method.
res.
Debug(). // Print response debug info.
Success(). // Ensure that response status code is in 2xx range.
Unmarshal(&data). // Unmarshal response body into variable.
Must() // Ensure that everything went fine, otherwise panic.
err := res.Error() // Get processing error. If someting went wrong on any chain stage, it will be here.
txt := res.Text() // Get response body as a string.