httpreq
JSON-over-HTTP calls on top of net/http with one function, options and typed errors.
go get github.com/ubgo/httpreq
- Language
- Go
- Go version
- 1.24
- Core deps
- 0 direct
- Latest tag
- v0.2.0
- License
- Apache-2.0
- Go modules
- 1
Highlights from the README
- Builds the request from options.
- Adds bearer or basic auth,
Content-Type, a default User-Agent, custom headers, and query params. - Encodes the body as JSON, URL-encoded form, or raw bytes.
- Sends with a per-request timeout and your context.
- Reads the body once.
- Returns
*HTTPErrorfor non-2xx (with the raw body captured), and can decode a structured error shape. - Routes the response into a JSON target, a raw
[]byte, or both.
Code from the README
import "github.com/ubgo/httpreq"
var resp UserResponse
_, err := httpreq.Do(ctx, "https://api.example.com/users",
httpreq.WithMethod(http.MethodPost),
httpreq.WithJSONBody(req),
httpreq.WithBearerToken(token),
httpreq.WithTimeout(5 * time.Second),
httpreq.WithResponseInto(&resp),
)form := url.Values{}
form.Set("grant_type", "client_credentials")
form.Set("scope", "read write")
var tok struct {
AccessToken string `json:"access_token"`
ExpiresIn int `json:"expires_in"`
}
_, err := httpreq.Do(ctx, "https://auth.example.com/oauth/token",
httpreq.WithMethod(http.MethodPost),
httpreq.WithBasicAuth(clientID, clientSecret),
httpreq.WithFormBody(form),
httpreq.WithResponseInto(&tok),
)cmd, _ := httpreq.Curl(ctx, "https://api/users",
httpreq.WithMethod(http.MethodPost),
httpreq.WithJSONBody(payload),
)
fmt.Println(cmd)
// curl -X POST -H 'Content-Type: application/json' --data-raw '{...}' 'https://api/users'_, err := httpreq.Do(ctx, "https://api/x")
var herr *httpreq.HTTPError
if errors.As(err, &herr) {
log.Printf("status=%d body=%s", herr.StatusCode, herr.Body)
}From the httpreq README.