美文网首页
Golang net/http

Golang net/http

作者: 勿以浮沙筑高台 | 来源:发表于2016-09-08 00:03 被阅读315次

http包提供了HTTP client和service的实现。

client#####

使用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"}})

一个Client是一个http客户端,Client的零值是一个使用DefaultTransport的可用的http客服端。Client的Transport具有内部状态(缓存TCP连接),所以一个Client应该被重复利用。一个Client可被多个goroutines安全地并发使用。

当client完成请求时必须close响应体:

resp, err := http.Get("http://google.com/")
if err != nil {
      panic(err)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
// ...```

http导出函数```Get( )```、```Head( )```、```Post( )```、```PostForm( )```提供了发起简单网络请求能力。
当需要控制请求头内容、重定向策略等... 这时候需要创建一个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)
// ...```

当需要控制http代理、TLS配置、keep-alive、http压缩等... 这时需要创建一个 Transport:

tr := &http.Transport{
    TLSClientConfig:    &tls.Config{RootCAs: pool},
    DisableCompression: true,
}
client := &http.Client{Transport: tr}
resp, err := client.Get("https://example.com")```

通过创建一个自定义服务器,可以对服务端的行为进行更多的控制:

s := &http.Server{
Addr: ":8080",
Handler: myHandler,
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
MaxHeaderBytes: 1 << 20,
}
log.Fatal(s.ListenAndServe())```

相关文章

  • Golang——net/http

    构建一个web 在浏览器输入http://localhost:8080 继承ServeHTTP net/http 路由

  • Golang net/http

    http包提供了HTTP client和service的实现。 client##### 使用http包提供的函数G...

  • golang net/http

    有时间再记录自己对go原生库net/http源码的解读,先开一篇文章,以免自己忘记

  • 无标题文章

    ``` // from golang: net/http/transport.go var portMap =ma...

  • http.ServeMux

    由于Web服务是HTTP协议的一个服务,Golang提供完善的net/http包,通过net/http包可以很方便...

  • golang net/http源码解析

    代码 http.HandleFunc("/hello", func(w http.ResponseWriter, ...

  • go 学习笔记

    这篇文章就总结一下go 的细节具体参考:http://c.biancheng.net/golang/[http:/...

  • [golang] fasthttp 使用http代理

    golang net/http标准库的client是可以配置各种代理的,http/https/sock5等,不过f...

  • go websocket

    获得相应包支持:go get golang.org/x/net/websocket 解释:(1)http.Hand...

  • golang grpc调用轨迹记录-trace

    在server端引入trace包 "golang.org/x/net/trace" //添加trace的http监...

网友评论

      本文标题:Golang net/http

      本文链接:https://www.haomeiwen.com/subject/qahjettx.html