Google资深工程师深度讲解Go语言-http及其他标准库(十一)

一.HTTP标准库

  • 使用http客户端发送请求
  • 使用http.client控制请求头部等
  • 使用httputil简化工作
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)
}

升级版

package main

import (
	"fmt"
	"net/http"
	"net/http/httputil"
)

func main() {
	request,err:=http.NewRequest(http.MethodGet,"http://www.imooc.com",nil)
	request.Header.Add("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{
		Transport:     nil,//设置代理服务器
		CheckRedirect: func( //重定向从这里过
			req *http.Request,
			via []*http.Request) error {
				fmt.Println("redirect:",req)
			return nil
		},
		Jar:           nil,//模拟登陆,设置cookie
		Timeout:       0,
	}
	resp,err:=client.Do(request)
	//resp,err:=http.DefaultClient.Do(request)
	//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",len(s))
}

二.http服务器的性能分析

  • import _"net/http/pprof"
  • 访问/debug/pprof
  • 使用 go tool pprof分析性能
import (
	"./filelisting"
	"log"
	"net/http"
	"os"
	_ "net/http/pprof"  //库前加下划线,引入库,使有pprof的能力
)

浏览器访问:file:///private/var/folders/w9/l38fmd696n95tmrt4pf980vm0000gn/T/pprof001.svg

标准库文档:https://studygolang.com/pkgdoc

或者使用:godoc -http localhost:6060,在本地查看

:

猜你喜欢

转载自blog.csdn.net/lxw1844912514/article/details/108540842