golang中的http库
1、http.Get
使用http.Get
发送请求
package main
import (
"fmt"
"net/http"
"net/http/httputil"
)
func main() {
resp, err := http.Get("http://www.imooc.com")
if err != nil {
panic(err)
}
defer resp.Body.Close()
//获取网页内容
s, err := httputil.DumpResponse(resp, true)
if err != nil {
panic(err)
}
fmt.Printf("%s\n", s)
}
2、http.DefaultClient.Do
使用http.DefaultClient.Do
发送请求
func main() {
request, err := http.NewRequest(
http.MethodGet,
"http://www.imooc.com", nil)
if err != nil {
panic(err)
}
request.Header.Add("User-Agent", "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)
fmt.Printf("%s", s)
}
3、http.Client
自定义http.Client
发送请求
func main() {
request, err := http.NewRequest(
http.MethodGet,
"http://www.imooc.com", nil)
if err != nil {
panic(err)
}
client := http.Client{
CheckRedirect: func(req *http.Request, via []*http.Request) error {
fmt.Println("Redirect:", req)
return nil
},
}
request.Header.Add("User-Agent", "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 := client.Do(request)
if err != nil {
panic(err)
}
defer resp.Body.Close()
s, err := httputil.DumpResponse( resp, true)
fmt.Printf("%s", s)
}
4、http服务器的性能分析
在使用golang开启一个http服务的时候,在import
中使用import _ "net/http/pprof"
可以使用命令分析http服务器性能