1、http标准库:
使用http客户端发送请求
使用http.Client控制请求头部等
使用httputil简化工作
func main(){
request,err := http.NewRequest(
http.MethodGet,
"http://jessiejacob.com",nil)
//加头部
request.Header.Add("User-Agent","Mozilla......") //key value 的形式添加头部信息
resp,err :=http.DefaultClient.Do(request)
//resp,err := http.Get("http:jessiejacob.com") //添加头部信息后就不能用http.Get的方式获取了,需要用client
if err != nil {
panic(err)
}
defer resp.Body.Close()
//dump请求的body
s,err := httputil.DumpResponse(resp,true)
if err != nil {
panic(err)
}
fmt.Printf("%s\n",s)
}
//也可以自己设置client
func main(){
request,err := http.NewRequest(
http.MethodGet,
"http://jessiejacob.com",nil)
//加头部
request.Header.Add("User-Agent","Mozilla......") //key value 的形式添加头部信息
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()
//dump请求的body
s,err := httputil.DumpResponse(resp,true)
if err != nil {
panic(err)
}
fmt.Printf("%s\n",s)
}
http服务器的性能分析
import _ “net/http/pprof” //加了_,就可以使用pprof而不报错
访问 /debug/pprof/
使用go tool pprof分析性能
go tool pprof http://localhost:8888/debug/pprof/profile
web
2、其他标准库:
bufio //提升速度
log
encoding/json
regexp //正则
time //time可以产生channel
strings/math/rand
看标准库的方法:
1、godoc -http :8888 //自己起服务器
2、https://studygolang.com/pkgdoc 里面有标准库中文版