Several common scenarios for sending HTTP requests in Golang

Source: Internet
Author: User
Tags readfile
This is a creation in Article, where the information may have evolved or changed.

Sort out how HTTP is sent in Golang

Some of the initial projects, a lot of places used to send HTTP requests to the Golang, and then the request received the results of some processing, the use of the pattern is also relatively fixed, here to organize the centralized HTTP send way, first record so much, and then add 1.1 points.

The most basic scenario

The way one uses HTTP. Newrequest

Mr. Cheng Http.client, re-generate http.request, then submit the request: client. Do (request) to process the return results, each step of the process can be set some specific parameters, the following is a simple and basic example:

//question ???将stdout重定向为response信息???package mainimport ("fmt""io""net/http""os")func main() {    //生成client 参数为默认client := &http.Client{}//生成要访问的urlurl := "http://www.baidu.com"    //提交请求reqest, err := http.NewRequest("GET", url, nil)if err != nil {panic(err)}//处理返回结果response, _ := client.Do(reqest)      //将结果定位到标准输出 也可以直接打印出来 或者定位到其他地方进行相应的处理stdout := os.Stdout_, err = io.Copy(stdout, response.Body)      //返回的状态码status := response.StatusCodefmt.Println(status)}

Way two Mr. Client.get/post into the client, and then with the.

The client structure itself has some methods of sending the API, such as Client.get,client.post,client.postform. Wait a minute. Basically covers the type of the main HTTP request, usually do not make any special configuration, so it can, in fact, the client's Get or Post method, is also on the HTTP. The Newerequest method is encapsulated with additional req added. Header.set ("Content-type", BodyType) general use, is also OK

Way three http. Get/post.

Implementation of the time, or the use of the previously mentioned pattern, Sir into a default client, then call HTTP. Newrequest method.

A detailed description of each step

Configuration of parameters when generating client

One of the most common parameters is the setting of the client side when sending information using HTTPS. If no information is added when the client is generated, the default value is used. The specific information includes:

Transport RoundTripperCheckRedirect func(req *Request, via []*Request) errorJar CookieJarTimeout time.Duration

The first parameter is a Roundtripper interface that contains a roundtrip function that specifies the basic mechanism of some HTTP requests. http. There are many parameters involved in transport, if not specified, the default defaulttransport parameter is used, which contains some default request time and proxy mechanism. Specific details of the parameters related to a lot, and some have not been used for example, those I shook hands time and so on, the most used is the relevant parameters of https: Tlsclientconfig, this is a *tls. Config type, which involves a lot of parameters, a basic is the case of the following, only in the configuration of the Rooca and client-side use of the certificate. The content of the relevant HTTPS can refer to the previous article

When sending an HTTPS request, the preceding parameters can be processed in the following way:

    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 generating the request

When generating a request, it is primarily a few basic parameters. The Newrequest function has three basic parameters, Newrequest (method, urlstr string, body io. Reader) The first is the type of request, GET, POST, PUT, etc. The form to be capitalized. The second parameter is the URL to which the request is to be accessed, and the third parameter is the contents of the requested body, which needs to be an IO. The type of reader.

Note IO. Reader interface is a read method, the implementation of the type of the Read method should be returned as Io.reader, read (p []byte) (n int, err error) function is the function of reading the Len (p) Length of the content into P, Returns the length of the read-in and the error message.

Strings is usually used. The Newreader function converts a string type to IO. Reader type, or bytes. The Newbuffer function converts the []byte type to IO. Reader type.

You can also add some additional information to the header of the request, such as the type of body requested and the token information added in the example below.

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

Also, for example, a mock-up form submission can set the type of submission as a URL. The values type is then encode:

// use map as structvar 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))

One of the most common cases where a JSON file is sent in the past can be set to the type of the header:

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

The rest of the sections are set up in the same way as before to send submissions.

The properties of the type of request are still more, and are organized slowly.

Processing of generated response results

Usually after the client is built, the client should be used. The Do method submits a client request and then returns a *response type. Response parameters in general also more, we need the most is usually the body parameters, generally through the body, _: = Ioutil. ReadAll (resp. Body) will convert the body to []byte type return, and then do other processing.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.