Detail several common cases of sending http requests in golang

  • 2020-08-22 22:11:58
  • OfStack

Method 1 USES http. Newrequest

Mr > http.request - > Then submit the request: ES12en. Do(request) - > Processing the returned results, each step can be set to a number of specific parameters, the following is a most basic example:


//question ??? will stdout Redirected to response Information?? 
package main

import (
  "fmt"
  "io"
  "net/http"
  "os"
)

func main() {
  // generate client  Parameter is default 
  client := &http.Client{}
  
  // Generate the ones to access url
  url := "http://www.baidu.com"
    
  // Submit a request 
  reqest, err := http.NewRequest("GET", url, nil)
  
  if err != nil {
    panic(err)
  }
  
  // Processing returns results 
  response, _ := client.Do(reqest)
  
  // Position the result to standard output   It can also be printed directly   Or locate somewhere else for processing 
  stdout := os.Stdout
  _, err = io.Copy(stdout, response.Body)
  
  // The status code returned 
  status := response.StatusCode

  fmt.Println(status)
}

Method 2 Mr. client, then client. get/post..

client structure itself also have 1 send api methods, such as client. get, client. post, client. postform.. And so on. Basically covers the main types of http requests, usually without any special configuration, and that's it. In fact, the get or post method of client is also the package of http.Newerequest method, with the addition of ES40en.Header.Set (" ES43en-ES44en ", bodyType)1, which is also ok

Method 3 http. Get/Post..

In the implementation, the pattern mentioned earlier is adopted. The default IS client, and then the method http.Newrequest is called.

Describe each step in detail

Configuration of parameters when client is generated

The most common parameter is the setting of the client terminal when sending messages using https. If client is generated without adding any information, the default value will be used. Specific information includes:

Transport RoundTripper CheckRedirect func(req *Request, via []*Request) error Jar CookieJar Timeout time.Duration

The first argument is an RoundTripper interface, which contains an RoundTrip function that specifies the basic mechanism for some http requests. http.Transport has a lot of parameters involved. If you do not specify it, the default DefaultTransport parameter is used, which contains 1 default request time and proxy mechanism etc. Specific details of the parameters involved in a lot of, some of them didn't use to like those I shook hands with time, such as the currently used in the most is the related parameters of https: TLSClientConfig, this is a * tls Config type, which involves the parameters of the still has a lot of, a use case is basic as follows, just set in the configuration rooca and customer end use certificate. Refer to the previous article for https

Normally when sending https requests, the preceding parameters can be handled as follows:


  pool := x509.NewCertPool()
  caCertPath := "certs/cert_server/ca.crt"

  caCrt, err := ioutil.ReadFile(caCertPath)
  if err != nil {
    fmt.Println("ReadFile err:", err)
    return
  }
  pool.AppendCertsFromPEM(caCrt)

  cliCrt, err := tls.LoadX509KeyPair("certs/cert_server/client.crt", "certs/cert_server/client.key")
  if err != nil {
    fmt.Println("Loadx509keypair err:", err)
    return
  }
  
  tr := &http.Transport{
    TLSClientConfig: &tls.Config{
      RootCAs:   pool,
      Certificates: []tls.Certificate{cliCrt},
    },
  }
  client := &http.Client{Transport: tr}

Parameter configuration when request is generated

When generating request, a few basic parameters are the main ones. The NewRequest function has three basic arguments, NewRequest(method, urlStr ES10106en, body io.Reader). The first is the type of request, GET, POST, PUT, etc. The second parameter is url to be accessed by the request, and the third parameter is the content in the request's body, which needs to be of type ES116en.Reader.

The Read(p []byte) (n int, err error) function is to read the length of len(p) into p, and return the length of the read and error message.

strings. NewReader function is usually used to convert one string type to ES141en. Reader type, or bytes. NewBuffer function to convert []byte type to ES146en. Reader type.

You can also add 1 additional information to header for request, such as the type of body requested and token information in the following example.


  reqest.Header.Set("Content-Type", "application/x-www-form-urlencoded")
  reqest.Header.Set("Authorization", "qwertyuiopasdfghjklzxcvbnm1234567890")

Another example is the simulation form submission. You can set the submission type to ES157en. Values and then Encode:


// use map as struct
  var clusterinfo = url.Values{}
  //var clusterinfo = map[string]string{}
  clusterinfo.Add("userName", user)
  clusterinfo.Add("password", pw)
  clusterinfo.Add("cloudName", clustername)
  clusterinfo.Add("masterIp", masterip)
  clusterinfo.Add("cacrt", string(caCrt))

  data := clusterinfo.Encode()
  
  url := "https://10.10.105.124:8443/user/checkAndUpdate"
  reqest, err := http.NewRequest("POST", url, strings.NewReader(data))

The most common one is to send an json file. In the past, the type of Header can be set to:


"Content-Type", "application/json; charset=utf-8"

The rest is set up in the same way as before and just send the commit.

request still has a lot of type attributes, slowly sort them out.

Processing of the generated response results

1 After the client is built, the client request is submitted using the ES178en.Do (request) method, after which 1 *Response type is returned. In response, the parameter 1 is also common. The most common parameter we need is Body. 1 is usually returned by body, _ := ioutil. ReadAll(resp. Body), which converts body to []byte and then does other processing.


Related articles: