Go study notes (76)-Go standard library net/http to create a client (send GET, POST requests)

1. Get request

1.1 Shortcut method GET using net/http package

package main

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

func main() {
    
    
	resp, err := http.Get("http://www.baidu.com")
	if err != nil {
    
    
		fmt.Println(err)
	}
	defer resp.Body.Close()
	
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
    
    
		fmt.Println(err)
	}
	fmt.Println(string(body))
}

1.2 Custom client

package main

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

func main() {
    
    
	client := &http.Client{
    
    }
	request, err := http.NewRequest("GET", "http://www.baidu.com", nil)
	if err != nil {
    
    
		fmt.Println(err)
	}

	resp, err := client.Do(request)
	if err != nil {
    
    
		fmt.Println(err)
	}
	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
    
    
		fmt.Println(err)
	}
	fmt.Println(string(body))
}

Use a custom HTTPclient means that the request to set headers, basic authentication and cookies. In view of the small difference between the code required to make the request when using the shortcut method and the custom HTTP client, it is recommended to use a custom HTTP client unless the task to be completed is very simple.

2. POST request

package main

import (
	"fmt"
	"io/ioutil"
	"net/http"
	"strings"
)

func main() {
    
    
	data := strings.NewReader(`{"some": "json"}`)
	resp, err := http.Post("https://httpbin.org/post", "application/json", data)
	if err != nil {
    
    
		fmt.Println(err)
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
    
    
		fmt.Println(err)
	}
	fmt.Println(string(body))
}

Output result:

{
    
    
  "args": {
    
    }, 
  "data": "{\"some\": \"json\"}", 
  "files": {
    
    }, 
  "form": {
    
    }, 
  "headers": {
    
    
    "Accept-Encoding": "gzip", 
    "Content-Length": "16", 
    "Content-Type": "application/json", 
    "Host": "httpbin.org", 
    "User-Agent": "Go-http-client/2.0", 
    "X-Amzn-Trace-Id": "Root=1-60575025-22341e95217463712e18068e"
  }, 
  "json": {
    
    
    "some": "json"
  }, 
  "origin": "192.168.0.110", 
  "url": "https://httpbin.org/post"
}

3. Debug HTTP

net/http/httputilAlso it provides the ability to make it easy for you to debug HTTPclient and server approach. The package method DumpRequestOutand DumpResponseallows you to view the request and response.

May be modified to the previous example, to use the net/http/httputilpackage DumpRequestOutand DumpResponse
methods to support the log function. These methods display the request and response headers, as well as the response body returned.

package main

import (
	"fmt"
	"io/ioutil"
	"net/http"
	"net/http/httputil"
	"strings"
)

func main() {
    
    
	client := &http.Client{
    
    }
	data := strings.NewReader(`{"some": "json"}`)

	request, err := http.NewRequest("POST", "https://httpbin.org/post", data)
	request.Header.Add("Accept", "application/json") // 增加请求报文头
	/*
		通过使用 Accept 报头, 客户端告诉服务器它想要的是 application/json,而服务器返回数
		据时将 Content-Type 报头设置成了application/json。

	*/
	if err != nil {
    
    
		fmt.Println(err)
	}

	debugReq, err := httputil.DumpRequestOut(request, true)
	if err != nil {
    
    
		fmt.Println(err)
	}
	fmt.Println("debugReq is ", string(debugReq))

	resp, err := client.Do(request)
	if err != nil {
    
    
		fmt.Println(err)
	}
	defer resp.Body.Close()

	debugResponse, err := httputil.DumpResponse(resp, true)
	if err != nil {
    
    
		fmt.Println(err)
	}
	fmt.Println("debugResponse is ", string(debugResponse))

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
    
    
		fmt.Println(err)
	}
	fmt.Println(string(body))
}

Output result:

debugReq is  POST /post HTTP/1.1
Host: httpbin.org
User-Agent: Go-http-client/1.1
Content-Length: 16
Accept: application/json
Accept-Encoding: gzip

{
    
    "some": "json"}
debugResponse is  HTTP/2.0 200 OK
Content-Length: 441
Access-Control-Allow-Credentials: true
Access-Control-Allow-Origin: *
Content-Type: application/json
Date: Sun, 21 Mar 2021 14:35:01 GMT
Server: gunicorn/19.9.0

4. Processing timeout

Use the default HTTPclient, it does not set the timeout request. This means that if the server does not respond, the request will wait or hang indefinitely. For any request, it is recommended to set a timeout period. In this way, if the request is not completed within the specified time, an error will be returned.

	client := &http.Client{
    
    
		Timeout: 1 * time.Second,
	}

The above configuration requires the client to complete the request within 1s. But because the server's response speed is not fast enough. It is entirely possible that the request timed out. as follows:

Post https://httpbin.org/post: net/http:
 request canceled (Client.Timeout exceeded while awaiting headers)
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x40 pc=0x63491b]

Guess you like

Origin blog.csdn.net/wohu1104/article/details/115057050