1.9 Go标准库深度解析:net/http、context、sync核心包实战应用
引言
Go语言的标准库功能强大且设计精良,其中net/http、context和sync是最常用的三个包。深入理解这些包的使用方法,能够大大提高开发效率。本文将详细解析这三个核心包的应用。
一、net/http包
1.1 HTTP服务器基础
packagemainimport("fmt""net/http")funchandler(w http.ResponseWriter,r*http.Request){fmt.Fprintf(w,"Hello, World!")}funcmain(){http.HandleFunc("/",handler)http.ListenAndServe(":8080",nil)}1.2 HTTP客户端
packagemainimport("fmt""io""net/http")funcmain(){// GET请求resp,err:=http.Get("https://www.example.com")iferr!=nil{panic(err)}deferresp.Body.Close()body,err:=io.ReadAll(resp.Body)iferr!=nil{panic(err)}fmt.Println(string(body))// POST请求resp2,err:=http.Post("https://httpbin.org/post","application/json",strings.NewReader(`{"key":"value"}`))iferr!=nil{panic(err)}deferresp2.Body.Close()}1.3 自定义HTTP客户端
packagemainimport("net/http""time")funcmain(){client:=&http.Client{Timeout:10*time.Second,Transport:&http.Transport{MaxIdleConns:100,MaxIdleConnsPerHost:10,IdleConnTimeout:90*time.Second,},}req,_:=http.NewRequest("GET","https://www.example.com",nil)req.Header.Set("User-Agent","MyApp/1.0")resp,err:=client.Do(req)iferr!=nil{panic(err)}deferresp.Body.Close()}二、context包
2.1 Context基础
packagemainimport("context""fmt""time")funcdoWork(ctx context.Context){for{select{case<-ctx.Done():fmt.Println("工作被取消")returndefault: