httpclient

We’ve seen how to write HTTP Server. Let’s see what client does this time

func main() { resp, err := http.Get("https://www.baidu.com") if err ! = nil { panic(err) } defer resp.Body.Close() s, err := httputil.DumpResponse(resp, true) if err ! = nil { panic(err) } fmt.Println(string(s)) }Copy the code

We request a Baidu home page to print down his return

You might wonder why string(s) is required if you look at dump it returns an array of bytes so you have to string it, otherwise it’s just pure bytes

And here we can of course set the header of the request

func main() { request,err:=http.NewRequest(http.MethodGet,"https://juejin.cn",nil) Request. The Header. The Add (" the user-agent ", "Mozilla / 5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, Like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1") resp, err := http.defaultClient. Do(request) if err! = nil { panic(err) } defer resp.Body.Close() s, err := httputil.DumpResponse(resp, true) if err ! = nil { panic(err) } fmt.Println(string(s)) }Copy the code

We can also customize clients to listen for redirects and other trace behavior in the request

func main() { request, err := http.NewRequest(http.MethodGet, "https://imooc.com", Nil) request. The Header. The Add (" the user-agent ", "Mozilla / 5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, Like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1") client := http. client {CheckRedirect: Func (req *http.Request, via []*http.Request) error {FMT.Println("redirect: ", req) return nil }, } resp, err := client.Do(request) if err ! = nil { panic(err) } defer resp.Body.Close() s, err := httputil.DumpResponse(resp, true) if err ! = nil { panic(err) } fmt.Println(string(s)) }Copy the code

Take a look at log printing

A brief introduction to other standard libraries

godoc -http :8888

You can open a local HTTP document with the command above

This bufio is designed to improve the efficiency of writing I/OS, by first writing numbers to cache and then flushing them to hard disk for the last time

The encoding JSON library is probably the most commonly used library by developers

Time libraries are also commonly used, such as time-outs

And then there’s string, Math, RAND, all of these other libraries that are available in other languages that you can learn on your own with GoDoc

In addition to the standard library we can also refer to studygolang.com/pkgdoc Chinese translation to learn