Simplifies HTTP client usage compared to net/http
Can't forget to close response body
Checks status codes by default
Supports context.Context
JSON serialization and deserialization helpers
No third party dependencies
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
POST a JSON object and parse the response
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 custom headers for a request
// Set headers
obj , err := goreq .New [string ]("https://postman-echo.com/get" ).
Headers ("User-Agent" , "bond/james-bond" ,
"Content-Type" , "secret" ,
"martini" , "shaken" ).
Fetch (ctx )
Easily manipulate URLs and query parameters
s , err := goreq .New [string ]("https://prod.example.com/get?a=1&b=2" ).
Params ("b" , "3" ,"c" , "4" ).Fetch (ctx )
In work