- Compress brotli, gzip, deflate
- Simplifies HTTP client usage compared to net/http
- Checks status codes by default
- Supports context.Context
- JSON serialization and deserialization on board
| code with net/http | code with requests |
|---|---|
req, err := http.NewRequestWithContext(ctx,
http.MethodGet, "http://example.com", nil)
if err != nil {
// ...
}
res, err := http.DefaultClient.Do(req)
if err != nil {
// ...
}
defer res.Body.Close()
b, err := io.ReadAll(res.Body)
if err != nil {
// ...
}
s := string(b) |
s, err := goreq.New[string]("http://example.com").
Fetch(context.Backgroun())
fmt.Println(s) |
| 11+ lines | 1 line |
| code with net/http | code with requests |
|---|---|
body := bytes.NewReader(([]byte(`hello, world`))
req, err := http.NewRequestWithContext(ctx, http.MethodPost,
"https://postman-echo.com/post", body)
if err != nil {
// ...
}
req.Header.Set("Content-Type", "text/plain")
res, err := http.DefaultClient.Do(req)
if err != nil {
// ...
}
defer res.Body.Close()
_, err := io.ReadAll(res.Body)
if err != nil {
// ...
} |
s, err := goreq.New[string]("https://postman-echo.com/post").
BodyRaw([]byte(`hello, world`)).
Header("Content-Type", "text/plain").
Fetch(ctx) |
| 12+ lines | 4 lines |
| code with net/http | code with requests |
|---|---|
var post placeholder
u, err := url.Parse("https://jsonplaceholder.typicode.com")
if err != nil {
// ...
}
u.Path = fmt.Sprintf("/posts/%d", 1)
req, err := http.NewRequestWithContext(ctx,
http.MethodGet, u.String(), nil)
if err != nil {
// ...
}
res, err := http.DefaultClient.Do(req)
if err != nil {
// ...
}
defer res.Body.Close()
b, err := io.ReadAll(res.Body)
if err != nil {
// ...
}
err := json.Unmarshal(b, &post)
if err != nil {
// ...
} |
post, err := goreq.New[placeholder]("https://jsonplaceholder.typicode.com").IsJson().
Path(fmt.Sprintf("/posts/%d", 1)).Fetch(ctx) |
| 18+ lines | 2 lines |
req := placeholder{
Title: "foo",
Body: "baz",
UserID: 1,
}
res, err := goreq.New[placeholder]("https://jsonplaceholder.typicode.com").
Path("/posts").BodyJson(req).IsJson().Fetch(ctx)
// net/http equivalent left as an exercise for the reader// Set headers
obj, _ := goreq.New[string](ctx, "https://postman-echo.com/get").
Headers("User-Agent", "bond/james-bond",
"Content-Type", "secret",
"martini", "shaken").
Fetch()str, _ := goreq.New[string](ctx, "https://prod.example.com/get?a=1&b=2").Params("b", "3","c", "4").Fetch()
//result url: https://prod.example.com/get?a=1&b=3&c=4github.com/andybalholm/brotli compressor and decompressor implemented in Go.