11、go语言:http及其他标准库

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 里面有标准库中文版

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值