Golang language minimalist HTTP client gorequest


Golang language minimalist HTTP client gorequest

1 Introduction

Gorequest is a minimalistHTTPClient, the author is inspired by the node.js library SuperAgent. comparisonGolangThe standard library, net / HTTP, makes gorequest easier to use. The official slogan of gorequest is “send a request like a machine gun”.

Gorequest includes the following functions:

  • HTTP request mode supported: get / post / put / head / delete / patch / options
  • Supports setting header request headers
  • JSON strings are supported as request parameters
  • It supports sending data and files in the form of multiple requests
  • Supports sending requests through agents
  • Supports setting timeout for requests
  • Support TLS client settings
  • Support setting redirection policy
  • Support for setting cookies for requests
  • CookieJar – automatic in-memory cookiejar
  • Support request header setting basic authentication

Installation method:

  1. gogetgithub.com/parnurzeal/gorequest

2http request mode

Golang sends a simple get request, using the net / HTTP standard library and the gorequst library. Both methods of sending get requests are relatively simple.

The example code is as follows:

Standard library method:

  1. resp,err:=http.Get(“http://example.com/”)

Gorequest library method:

  1. request:=gorequest.New()
  2. resp,body,errs:=request.Get(“http://example.com/”).End()

Or (the gorequest method cannot reuse objects)

  1. resp,body,errs:=gorequest.New().Get(“http://example.com/”).End()

After reading the above two codes, we can find that sending get requests using the standard library is even simpler than sending get requests using the gorequest library.

However, when we need to make some modifications, for example, we need to set the header header and redirect policy for get requests. Let’s take another look at the implementation methods of using the standard library and gorequest library respectively.

Standard library method:

  1. client:=&http.Client{
  2. CheckRedirect:redirectPolicyFunc,
  3. }
  4. req,err:=http.NewRequest(“GET”,”http://example.com”,nil)
  5. req.Header.Add(“If-None-Match”,`W/”wyzzy”`)
  6. resp,err:=client.Do(req)

Gorequest library method (other HTTP request methods are the same as get):

  1. request:=gorequest.New()
  2. resp,body,errs:=request.Get(“http://example.com”).
  3. RedirectPolicy(redirectPolicyFunc).
  4. Set(“If-None-Match”,`W/”wyzzy”`).
  5. End()

After reading the above two pieces of code, it is easy to find that using gorequest makes the implementation easier. Using the standard library method, you first need to create a client, and then use different commands to set header operations, just to implement an HTTP request. Using the gorequest method, it can be easily realized by chain calling two methods.

3json format request parameters

In the golang language, if you use the standard library net / HTTP to send a post request with the request parameter in JSON format, you first need to convert the data of map or struct type, use the marshal method of the standard library encoding / JSON to convert the data into JSON format, set the value of the header header header parameter content type to application / JSON, and then create a client, Eventually your code gets longer and harder to maintain.

Standard library method:

  1. m:=map[string]interface{}{
  2. “name”:”backy”,
  3. “species”:”dog”,
  4. }
  5. mJson,_:=json.Marshal(m)
  6. contentReader:=bytes.NewReader(mJson)
  7. req,_:=http.NewRequest(“POST”,”http://example.com”,contentReader)
  8. req.Header.Set(“Content-Type”,”application/json”)
  9. req.Header.Set(“Notes”,”GoRequestiscoming!”)
  10. client:=&http.Client{}
  11. resp,_:=client.Do(req)

If you use the gorequest library to send a post request with the request parameters in JSON format, it only needs one line of code because it supports the request parameters in JSON format by default.

Gorequest library method:

  1. request:=gorequest.New()
  2. resp,body,errs:=request.Post(“http://example.com”).
  3. Set(“Notes”,”gorequstiscoming!”).
  4. Send(`{“name”:”backy”,”species”:”dog”}`).
  5. End()

4. Callback function is supported

The gorequest library also supports callback functions. You can use them flexibly according to your project requirements. The example code of callback functions is as follows:

  1. funcprintStatus(respgorequest.Response,bodystring,errs[]error){
  2. fmt.Println(resp.Status)
  3. }
  4. gorequest.New().Get(“http://example.com”).End(printStatus)

5 request control

In the development of golang project, sometimes we may need to make some additional controls on requests, such as timeout processing, retry request n times, redirection processing, etc. Gorequest library can provide us with a simple implementation.

Timeout processing:

  1. request:=gorequest.New().Timeout(2*time.Millisecond)
  2. resp,body,errs:=request.Get(“http://example.com”).End()

It should be noted that timeout is the total time spent on dial connection and IO reading and writing, which is compared with the time parameter.

Retry request:

  1. request:=gorequest.New()
  2. resp,body,errs:=request.Get(“http://example.com/”).
  3. Retry(3,5*time.Second,http.StatusBadRequest,http.StatusInternalServerError).
  4. End()

Reading the above code means that when the server returns http.statusbadrequest or http.statusinternalservererror, the request will be retried every 5 seconds for a total of 3 times.

Redirect processing:

  1. request:=gorequest.New()
  2. resp,body,errs:=request.Get(“http://example.com/”).
  3. RedirectPolicy(func(reqRequest,via[]*Request)error{
  4. ifreq.URL.Scheme!=”https”{
  5. returnhttp.ErrUseLastResponse
  6. }
  7. }).
  8. End()

Read the above code, which means redirecting HTTP requests to HTTPS requests.

6 return result processing method

Readers may have found that the above example code ends with end. End means that the returned result is of string type. If we want the returned result to be of other types, such as byte type and structure type, we can replace end with endbytes and endstruct respectively.

Endbytes format:

  1. resp,bodyBytes,errs:=gorequest.New().Get(“http://example.com/”).EndBytes()

Endstruct format:

  1. heyYoustruct{
  2. Heystring`json:”hey”`
  3. }
  4. varheyYouheyYou
  5. resp,_,errs:=gorequest.New().Get(“http://example.com/”).EndStruct(&heyYou)

7 Summary

In this article, we introduce the minimalist HTTP client gorequest of golang language and its usage. It is simpler to use than the standard library net / HTTP. When we need to use HTTP to call the interface in project development, we strongly recommend using the gorequest library.

The underlying layer of gorequest is implemented based on HTTP. Client in most use cases, so the object obtained by calling gorequest. New() once should be used as many times as possible.

In addition to the JSON parameters described above, gorequest also supports struct and file. Interested readers can refer to the official documents for relevant contents.