总结下Golang net/http标准库常用方法

Go语言的net/http标准库提供了构建HTTP服务器和客户端的基础设施。以下是一些常用方法的总结:

HTTP服务器相关

  1. http.ListenAndServe:启动一个HTTP服务器并监听指定的地址和端口。
err := http.ListenAndServe(":8080", nil)
  1. http.HandleFunc:将一个HTTP路由映射到一个处理器函数。
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
    w.Write([]byte("Hello, World!"))
})
  1. http.ServeFile:使用HTTP响应来服务一个文件。
http.HandleFunc("/static/", func(w http.ResponseWriter, r *http.Request) {
    http.ServeFile(w, r, r.URL.Path[1:])
})
  1. http.FileServer:返回一个可以提供目录文件服务的http.Handler
http.Handle("/", http.FileServer(http.Dir("./static")))
  1. http.ServeMux:一个ServeMux用于多路复用HTTP请求到不同的处理器。
mux := http.NewServeMux()
mux.HandleFunc("/", HomeHandler)
mux.HandleFunc("/about", AboutHandler)
  1. http.ResponseWriter:一个接口,用于写入HTTP响应。
w.Header().Set("Content-Type", "text/plain")
w.Write([]byte("Hello, World!"))

HTTP客户端相关

  1. http.Get:执行一个简单的HTTP GET请求。
resp, err := http.Get("http://example.com")
  1. http.Post:执行一个HTTP POST请求。
resp, err := http.Post("http://example.com/upload", "image/jpeg", &buf)
  1. http.NewRequest:创建一个新的HTTP请求。
req, err := http.NewRequest("GET", "http://example.com", nil)
  1. http.Client:执行一个HTTP请求,并返回一个http.Response
client := &http.Client{}
resp, err := client.Do(req)
  1. http.Client.Post:使用http.Client执行一个POST请求。
resp, err := client.Post("http://example.com/upload", "application/json", bytes.NewBuffer(data))
  1. http.Client.Do:执行一个给定的HTTP请求,并返回一个http.Response
resp, err := client.Do(req)
  1. http.ReadResponse:从io.Reader读取并解析HTTP响应。
resp, err := http.ReadResponse(bufio.NewReader(reader), req)

其他常用功能

  1. http.ParseHTTPVersion:解析HTTP版本字符串。
major, minor, err := http.ParseHTTPVersion("HTTP/1.1")
  1. http.StatusText:返回HTTP状态码对应的文本。
text := http.StatusText(404)
  1. http.DetectContentType:根据提供的块数据来检测MIME类型。
contentType := http.DetectContentType(data)
  1. http.Cookie:表示一个HTTP cookie,并实现了encoding.TextMarshalerencoding.TextUnmarshaler接口。
cookie := &http.Cookie{Name: "name", Value: "value"}
  1. http.SetCookie:写入一个cookie到HTTP响应头中。
http.SetCookie(w, cookie)
  1. http.ParseCookie:解析HTTP请求头中的Cookie字段。
cookie, err := http.ParseCookie(r.Header.Get("Cookie"))

这些方法为处理HTTP请求和响应提供了基本的构建块,允许开发者构建功能丰富的HTTP服务和客户端。在使用net/http包时,还应考虑错误处理、超时管理、保持连接活跃等高级特性。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值