Go study notes(76)-標準ライブラリnet / httpに移動してクライアントを作成します(GET、POSTリクエストを送信します)

1.リクエストを取得する

1.1 net / httpパッケージを使用したショートカットメソッドGET

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カスタムクライアント

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))
}

カスタムHTTPクライアントを使用するということは、ヘッダー、基本認証、およびCookieを設定する要求を意味します。ショートカットメソッドとカスタムHTTPクライアントを使用する場合、リクエストを行うために必要なコードにほとんど違いがないという事実を考慮して、完了するタスクが非常に単純でない限り、カスタムHTTPクライアントを使用することをお勧めします。

2.POSTリクエスト

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))
}

出力結果:

{
    
    
  "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.HTTPをデバッグします

net/http/httputilまた、HTTPクライアントとサーバーのアプローチを簡単にデバッグできるようにする機能も提供します。パッケージメソッドでDumpRequestOutありDumpResponse、要求と応答を表示できます。

net/http/httputilパッケージDumpRequestOutDumpResponse
メソッドを使用してログ機能をサポートするために、前の例に変更できます。これらのメソッドは、要求ヘッダーと応答ヘッダー、および返された応答本文を表示します。

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))
}

出力結果:

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.処理タイムアウト

デフォルトのHTTPクライアントを使用します。タイムアウト要求は設定されません。これは、サーバーが応答しない場合、要求は無期限に待機またはハングすることを意味します。リクエストには、タイムアウト期間を設定することをお勧めします。そのため、指定された時間内にリクエストが完了しなかった場合、エラーが返されます。

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

上記の構成では、クライアントは1秒以内にリクエストを完了する必要があります。しかし、サーバーの応答速度が十分に速くないためです。リクエストがタイムアウトした可能性があります。次のように:

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]

おすすめ

転載: blog.csdn.net/wohu1104/article/details/115057050