In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly introduces the example analysis of http request in golang, which has a certain reference value. Interested friends can refer to it. I hope you can learn a lot after reading this article.
Http requests in golang
There is a native http dependency library in golang: both the establishment of the net/http,http server and the development of the http client will use this dependency library. Here we mainly explain the client part, which is used as the request initiator for daily interface testing. The example code is as follows:
Get request
Package mainimport ("fmt"io/ioutil"net/http") func main () {/ / simulate a get submit request resp, err: = http.Get ("http://127.0.0.1:12345/checkon") if err! = nil {panic (err)} defer resp.Body.Close () / / close the connection body, err: = ioutil.ReadAll (resp.Body) / / read the contents of body fmt.Println (string (body))}
Return the result
E:\ go_project > go run testget.go {"code": 200, "data": "", "msg": "online", "state": "success"}
Post request:
Package mainimport ("fmt"io/ioutil"net/http"strings") func main () {/ / simulate a post submission request resp, err: = http.Post ("http://www.baidu.com"," application/x-www-form-urlencoded ", strings.NewReader (" id=1 ")) if err! = nil {panic (err)} / / close the connection defer resp.Body.Close () / / read all the contents in the message body Err: = ioutil.ReadAll (resp.Body) / / output content fmt.Println (string (body))}
The above post request is in the form of form and ends up returning a page
Explain the following line of code here
Defer resp.Body.Close ()
The first is defer, the defer statement of Go is used to schedule a function call (deferred function) so that it is run before the function executing defer is about to return, and the parameters of the deferred function (including the recipient) are actually evaluated when the defer is executed, not when the call is executed. That is to say, the parameters of the delayed function are evaluated in normal order, which is simply understood as: no matter where the code line corresponding to defer is placed in the code snippet, defer is the line of code executed before return, but the parameters in the line of defer need to be declared before being called. Corresponding to the processing in the response, the Response.Body of golang needs to be turned off, and body is actually a nested multi-tier net.TCPConn:
Bufio.Reader, which attempts to replace multiple small reads with one big read, reducing the number of system calls and improving performance
The io.LimitedReader,tcp connection will not be closed after reading the body, and continuing to read will cause blocking, so it is necessary for LimitedReader to issue an eof to terminate the reading after the body has finished reading.
ChunkedReader, parsing chunked format encoding (if not skipped by chunked)
BodyEOFSignal, when reading eof or shutting down body in advance, will notify readLoop to reclaim the connection.
GzipReader, parsing gzip compression (if not gizp compression skipped)
It can be seen from the above that if the body is neither fully read nor closed, the http transaction will not be completed this time. Unless the connection is terminated due to a timeout, the relevant resources cannot be reclaimed, so we need to close the connection. This is a point that many golang novices will ignore. When dealing with response as a client side, body must close, otherwise the GC will not be reclaimed, resulting in memory leakage.
Post request with json
Most of the restful interfaces we apply are request bodies in json format, and the corresponding golang http requests will also have related ways post json request bodies
Package mainimport ("fmt"io/ioutil"net/http"bytes"encoding/json") type HttpData struct {Flag int `json: "flag" `Msg string `json: "msg" `} func main () {url: = "http://127.0.0.1:12345/postdata" contentType: =" application/json " Charset=utf-8 "var httpdata HttpData httpdata.Flag = 1 httpdata.Msg =" terrychow "b, err: = json.Marshal (httpdata) if err! = nil {fmt.Println (" json format error: ", err) return} body: = bytes.NewBuffer (b) resp, err: = http.Post (url, contentType, body) if err! = nil {fmt.Println (" Post failed: ", err) return} defer resp.Body.Close () content Err: = ioutil.ReadAll (resp.Body) if err! = nil {fmt.Println ("Read failed:", err) return} fmt.Println ("header:", resp.Header) fmt.Println ("content:", string (content))}
Execution result response
E:\ go_project > go run gohttptest.goheader: map [Content-Type: [application/json] Content-Length: [78] Server: [Werkzeug/0.14.1 Python/2.7.15] Date: [Thu, 06 Dec 2018 16:35:11 GMT]] content: {"code": 200, "data": 1, "msg": "terrychow", "state": "success"}
The commonly used get and post requests are basically executed according to the above version. Of course, what we need to do now is to test the http interface, so we need to introduce a testing framework for related verification. This article first explains how to use the previously mentioned gocheck to make assertions.
Http Interface Test in golang
After introducing gocheck, we got the following script:
Package hello_testimport ("testing"fmt"strconv"io/ioutil"net/http"bytes"encoding/json". "gopkg.in/check.v1") var an int = 1type HttpData struct / Hook up gocheck into the "go test" runner.func Test (t * testing.T) {TestingT (t)} type MySuite struct {} type HttpData struct {Flag int `json: "flag" `Msg string `json: "msg" `} var _ = Suite (& MySuite {}) var testurl string = "http://127.0.0.1:12345"func (s * MySuite) SetUpSuite (c * C) {str3:=" for the first time The package starts executing "fmt.Println (str3) / / c.Skip (" Skip TestSutie ")} func (s * MySuite) TearDownSuite (c * C) {str4:=" first suite execution complete "fmt.Println (str4)} func (s * MySuite) SetUpTest (c * C) {str1:=" + strconv.Itoa (a) + "use case starts" fmt.Println (str1)} func (s * MySuite) TearDownTest (c * C) {str2: = "strconv.Itoa (a) +" use case execution completed "fmt.Println (str2) a=a+1} func (s * MySuite) TestHttpGet (c * C) {geturl: = fmt.Sprintf ("% v/checkon ") Testurl) respget, err: = http.Get (geturl) if err! = nil {panic (err)} defer respget.Body.Close () / / close the connection body, err: = ioutil.ReadAll (respget.Body) / / read the contents of body var gdat mapping [string] interface {} / / define the content map uses to parse resp.body if err: = json.Unmarshal ([] byte (string (body)), & gdat) Err = = nil {fmt.Println (gdat)} else {fmt.Println (err)} var gmsg=gdat ["msg"] c.Assert (gmsg, Equals, "terrychow") / / assertion of simulation failure} func (s * MySuite) TestHttpPost (c * C) {url: = fmt.Sprintf ("% v/postdata", testurl) contentType: = "application/json" Charset=utf-8 "var httpdata HttpData httpdata.Flag = 1 httpdata.Msg =" terrychow "b, err: = json.Marshal (httpdata) if err! = nil {fmt.Println (" json format error: ", err) return} body: = bytes.NewBuffer (b) resp, err: = http.Post (url, contentType, body) if err! = nil {fmt.Println (" Post failed: ", err) return} defer resp.Body.Close () content Err: = ioutil.ReadAll (resp.Body) if err! = nil {fmt.Println ("Read failed:", err) return} var dat map [string] interface {} / / defines what map uses to parse resp.body if err: = json.Unmarshal ([] byte (string (content)), & dat) Err = = nil {fmt.Println (dat)} else {fmt.Println (err)} var msg=dat ["msg"] c.Assert (msg, Equals, "terrychow") / / simulated successful assertion}
The final output:
E:\ go_project > go test-v gocheckhttp_test.go=== RUN Test 1st suite starts execution 1st use case starts map [code:200 data: msg:online state:success] 1st use case execution complete-- -FAIL: gocheckhttp_test.go:56: MySuite.TestHttpGetgocheckhttp_test.go:72: c.Assert (gmsg Equals, "terrychow"). Obtained string = "online"... Expected string = "terrychow" the second use case starts to execute map [msg:terrychow state:success code:200 data:1] the second use case execution completes the first suite execution complete OOPS: 1 passed, 1 FAILED--- FAIL: Test (0.02s) FAILFAIL command-line-arguments 0.613s
The output results are as expected, which is also a relatively basic http interface test.
Thank you for reading this article carefully. I hope the article "sample Analysis of http requests in golang" shared by the editor will be helpful to you. At the same time, I also hope you will support us and follow the industry information channel. More related knowledge is waiting for you to learn!
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.