Go基础之标准库

一.http库

  go作为一门面向服务,面向并发的语言,其http库是一个很重要的库.

  • 使用http客户端发送请求
  • 使用http.Client控制请求头部等
  • 使用httputil简化工作

import "net/http"

  http包提供了HTTP客户端和服务端的实现。

客户端:

  • Get、Head、Post和PostForm函数发出HTTP/ HTTPS请求。
  resp, err := http.Get("http://example.com/")
  ...
  resp, err := http.Post("http://example.com/upload", "image/jpeg", &buf)
  ...
  resp, err := http.PostForm("http://example.com/form",
	url.Values{"key": {"Value"}, "id": {"123"}})
  • 程序在使用完回复后必须关闭回复的主体。
  resp, err := http.Get("http://example.com/")
  if err != nil {
   	  // handle error
  }
  defer resp.Body.Close()
  body, err := ioutil.ReadAll(resp.Body)
  // ...
  • 要管理HTTP客户端的头域、重定向策略和其他设置,创建一个Client:
  client := &http.Client{
 	  CheckRedirect: redirectPolicyFunc,
  }
  resp, err := client.Get("http://example.com")
  // ...
  req, err := http.NewRequest("GET", "http://example.com", nil)
  // ...
  req.Header.Add("If-None-Match", `W/"wyzzy"`)
  resp, err := client.Do(req)
  // ...
  • 要管理代理、TLS配置、keep-alive、压缩和其他设置,创建一个Transport:
  tr := &http.Transport{
	  TLSClientConfig:    &tls.Config{RootCAs: pool},
	  DisableCompression: true,
  }
  client := &http.Client{Transport: tr}
  resp, err := client.Get("https://example.com")
  • Client和Transport类型都可以安全的被多个go程同时使用。出于效率考虑,应该一次建立、尽量重用。

服务端:

  • ListenAndServe使用指定的监听地址和处理器启动一个HTTP服务端。处理器参数通常是nil,这表示采用包变量DefaultServeMux作为处理器。Handle和HandleFunc函数可以向DefaultServeMux添加处理器。
  http.Handle("/foo", fooHandler)
  http.HandleFunc("/bar", func(w http.ResponseWriter, r *http.Request) {
	  fmt.Fprintf(w, "Hello, %q", html.EscapeString(r.URL.Path))
  })
  log.Fatal(http.ListenAndServe(":8080", nil))
  • 要管理服务端的行为,可以创建一个自定义的Server:
  s := &http.Server{
	  Addr:           ":8080",
	  Handler:        myHandler,
	  ReadTimeout:    10 * time.Second,
	  WriteTimeout:   10 * time.Second,
	  MaxHeaderBytes: 1 << 20,
  }
  log.Fatal(s.ListenAndServe())

 

http服务器的性能分析:

  1. import  _  "net/http/pprof"
  2. 访问/dbug/pprof/
  3. 使用 go tool pprof 分析性能

二.其他标准库 

  • bufio
  • log
  • encoding/json
  • regexp
  • time
  • string/math/rand
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值