Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How does the httpclient of golang initiate a http request

2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly explains "how the httpclient of golang initiates the http request". The content of the explanation is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "how the httpclient of golang initiates the http request".

1. Httpclient of net/http initiates http request

Method

Get request

Func httpGet () {

Resp, err: = http.Get ("http://www.01happy.com/demo/accept.php?id=1")

If err! = nil {

/ / handle error

}

Defer resp.Body.Close ()

Body, err: = ioutil.ReadAll (resp.Body)

If err! = nil {

/ / handle error

}

Fmt.Println (string (body))

}

Post request

Method 1: http.Post method

Func httpPost () {

Resp, err: = http.Post ("http://www.01happy.com/demo/accept.php",

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

}

Using this method, the second parameter (contentType) must be set to "application/x-www-form-urlencoded", otherwise the post parameter cannot be passed

Method 2: http.PostForm method

Func httpPostForm () {

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

}

Complex requests: if you need to set the request header parameters, data such as cookie, use the http.Do method

Func httpDo () {

Client: = & http.Client {}

Req, err: = http.NewRequest ("POST", "http://www.01happy.com/demo/accept.php", strings.NewReader (" name=cjb "))

If err! = nil {

/ / handle error

}

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

Req.Header.Set ("Cookie", "name=anny")

Resp, err: = client.Do (req)

Defer resp.Body.Close ()

Body, err: = ioutil.ReadAll (resp.Body)

If err! = nil {

/ / handle error

}

Fmt.Println (string (body))

}

Head request: Head method, which returns only the first part of the page

Note:

To call resp.Body.Close () to close response.body. If the resp.body is not closed, the underlying Client RoundTripper will not be able to reuse the existing TCP connection to serve the next request

The second step: the implementation of Do/Get/Post method (taking Do as an example)

Process the request and add referer and method fields

Call the send method to add cookie to request

Check whether the http header is legal. If it is legal to call the RoundTrip method of transport,

Step 3: essence: call the RoundTrip method of transport

+ + transport.go:++

Struct:

Type Transport struct {

IdleMu sync.Mutex

WantIdle bool / / user has requested to close all idle conns

IdleConn map [connectMethodKey] [] * persistConn

IdleConnCh map [connectMethodKey] chan * persistConn

ReqMu sync.Mutex

ReqCanceler map [* Request] func ()

AltMu sync.RWMutex

AltProto map [string] RoundTripper / / nil or map of URI scheme = > RoundTripper

/ / Dial gets a tcp connection, that is, the net.Conn structure, and remember that you can write request into it

/ / and then get response from it.

Dial func (network, addr string) (net.Conn, error)

}

Two map:

IdleConn: holds the mapping from connectMethodKey (representing different protocols, different host, that is, different requests) to persistConn

IdleConnCh: used to send persistent connections to each other in multiple goroutine when concurrent http requests, that is, these persistent connections can be reused, your http request has been used up with a certain persistConn, and this persistConn is sent to other http requests through this channel.

= = connection pool: =

RoundTrip method:

Func (t * Transport) RoundTrip (req * Request) (resp * Response, err error) {

...

Pconn, err: = t.getConn (req, cm)

If err! = nil {

T.setReqCanceler (req, nil)

Req.closeBody ()

Return nil, err

}

Return pconn.roundTrip (treq)

}

Omit the check of the parameters before, there are two main steps:

Step 1: get TCP persistent connection pconn, err: = t.getConn (req, cm)

Func (t * Transport) getConn (req * Request, cm connectMethod) (* persistConn, error) {

...

Type dialRes struct {

Pc * persistConn

Err error

}

Dialc: = make (chan dialRes)

/ / defines a channel that sends persistConn

...

/ / A goroutine is started, which is obtained by calling dialConn in the goroutine acquisition

/ / persistConn, and then send it to the channel dialc established above

Go func () {

Pc, err: = t.dialConn (cm)

Dialc

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report