net包 http - golang

 在上一篇文章中,主要學習了一下dial,主要用於一些tcp或者udp的socket連接。今天我們來看看net包中的http請求。

 在go中,主要給我們封裝了4個基礎請求讓我們可以快速實現http請求,他們分別是:

 http.Get(url string)

 http.Head(url string)

 http.Post(url, contentType string, body io.Reader)

 http.PostFrom(url string, data url.Values)

然後讓我們看看他們的關係:

從上圖我們可以看出,他們最終都是把請求體通過NewRequest()處理,然後傳入c.Do()處理返回。以http.Get爲例代碼爲:

func Get(url string) (resp *Response, err error) {
	return DefaultClient.Get(url)
}


func (c *Client) Get(url string) (resp *Response, err error) {
	req, err := NewRequest("GET", url, nil)
	if err != nil {
		return nil, err
	}
	return c.Do(req)
}

其他幾個請求大體和這個相似,只不過NewRequest()傳入數據不同。具體大家可以自己查看一下源碼。

由此可見,我們通過對NewRequest() 和 c.Do() 的調用就可以很簡單的實現各種http請求。

下面我們看一下,各個請求的使用方法:

http.Get() 很簡單我們只需要填入URL即可,代碼如下

    resp, err := http.Get("http://www.e.com/demo?id=1")
    if err != nil {
        // handle error
    }
 
    defer resp.Body.Close()
    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        // handle error
    }

http.Post()  和 http.PostFrom 是一種請求,通過上圖我們也可以看出postfrom是對post的進一步封裝。我們看看如何postfrom是怎麼調用post的:

func (c *Client) PostForm(url string, data url.Values) (resp *Response, err error) {
	return c.Post(url, "application/x-www-form-urlencoded", strings.NewReader(data.Encode()))
}

http.post()請求爲:

    resp, err := http.Post("http://www.aa.com/demo/",
        "application/x-www-form-urlencoded",
        strings.NewReader("name=cjb"))
    if err != nil {
        fmt.Println(err)
    }
 
    defer resp.Body.Close()
    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        // handle error
    }
 
    fmt.Println(string(body))

http.PostFrom()請求爲:

resp, err := http.PostForm("http://www.01happy.com/demo/accept.php",
        url.Values{"key": {"Value"}, "id": {"123"}})
 
    if err != nil {
        // handle error
    }
 
    defer resp.Body.Close()
    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        // handle error
    }
 
    fmt.Println(string(body))

最後讓我們看看如何用newrequest和c.do實現:

postValue := url.Values{
"email": {"[email protected]"},
"password": {"123456"},
}
 
postString := postValue.Encode()
 
req, err := http.NewRequest("POST","http://www.aa.com/demo", strings.NewReader(postString))
if err != nil {
// handle error
}
 
// 表單方式(必須)
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
//AJAX 方式請求
req.Header.Add("x-requested-with", "XMLHttpRequest")
 
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
// handle error
}
 
defer resp.Body.Close()
 
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
// handle error
}
 
fmt.Println(string(body))

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章