This article introduces an Http request wrapper library under Golang. You can configure request and processing returns similar to Python’s Requests library.
Get Goreq
go get -u github.com/zhshch2002/goreq
Copy the code
Quick start
First, let’s make a GET request. The code is very simple. As follows:
func main(a) {
res := goreq.Do(goreq.Get("https://httpbin.org/get"))
ifres.Err ! =nil {
fmt.Println(res.Err)
} else {
fmt.Println(res.Text)
}
}
Copy the code
Res contains the corresponding data. If res.Err is not null, an error has been encountered in the request.
In addition to GET, HTTP has a number of other methods, including POST, PUT, DELETE, HEAD, and OPTIONS. Change goreq.Get to goreq.Post.
func main(a) {
res := goreq.Post("https://httpbin.org/post").Do()
ifres.Err ! =nil {
fmt.Println(res.Err)
} else {
fmt.Println(res.Text)
}
}
Copy the code
The URL parameter
In UR? L key – value pair data separated by &. Building urls by hand is a bit more cumbersome, and we can just use the chained functions provided by Goreq.
func main(a) {
res := goreq.Get("https://httpbin.org/get?hi=myself").
AddParam("aaa"."111"). // set a single param
AddParams(map[string]string{
"bbb": "222",
}).Do()
ifres.Err ! =nil {
fmt.Println(res.Err)
} else {
fmt.Println(res.Text)
}
}
Copy the code
The URL of the request is https://httpbin.org/get?hi=myself&aaa=111&bbb=222. Goreq automatically encodes parameters.
From this, we can see the way Gore configures requests – the chain configuration. It is much faster than the original HTTP library provides.
The original way parameters are constructed.
req, err := http.NewRequest(http.MethodGet, "http://httpbin.org/get".nil)
iferr ! =nil {
panic(err)
}
params := make(url.Values) // The parameters are listed here
params.Add("key1"."value1")
params.Add("key2"."value2")
req.URL.RawQuery = params.Encode()
r, err := http.DefaultClient.Do(req)
Copy the code
The re-conversion of the data structure interrupted the original programming thought.
Goreq Configuration request
AddParam(k, v string)
Add URL parameterAddParams(v map[string]string)
Add a set of URL parametersAddHeader(key, value string)
Add request headersAddHeaders(v map[string]string)
Add a set of request headersAddCookie(c *http.Cookie)
Add a CookieSetUA(ua string)
Set the UASetBasicAuth(username, password string)
Set HTTP authenticationSetProxy(urladdr string)
Set up the proxy for this requestSetTimeout(t time.Duration)
Set a timeout for this requestDisableRedirect()
Disable redirection followingSetCheckRedirect(fn func(req *http.Request, via []*http.Request) error)
Set the redirection follow check function for this request- Setting POST Data
SetBody(b io.Reader)
SetRawBody(b []byte)
SetFormBody(v map[string]string)
SetJsonBody(v interface{})
SetMultipartBody(data ... interface{})
Set the data in Multipart format
Callback(fn func(resp *Response)
Set anDo
The callback function that executes after the method call completes
The response data
func main(a) {
res := goreq.Post("https://httpbin.org/post").Do()
fmt.Println(res.Body) // []byte data in byte format
fmt.Println(res.Text) // Automatically process the encoded parsed string
}
Copy the code
Originally designed as a library for apis and web requests, Goreq automatically inferred encoding types based on the response content and response headers, and automatically resolved to strings.
If we’re dealing with jSON-formatted response data, this can be more elegant.
func main(a) {
var data map[string]interface{}
err := goreq.Post("https://httpbin.org/post").Do().BindJSON(&data)
fmt.Println(data, err)
}
Copy the code
Goreq provides some quick ways to parse the Response RES. * Goreq.Response can be used to retrieve the Response data.
Resp() (*Response, error)
Get the response itself and the network request error.Txt() (string, error)
Automatically handles encoded and parsed text content and network request errors.HTML() (*goquery.Document, error)
XML() (*xmlpath.Node, error)
BindXML(i interface{}) error
JSON() (gjson.Result, error)
BindJSON(i interface{}) error
Error() error
Network request error. (In normal circumstancesnil
)
“One more thing,” Torre said.
This is basically how Goreq works, but for a more complete API, see GitHub. It also includes the use of custom clients and middleware.