如何在golang的net/http中使用Transport添加头信息

huangapple go评论89阅读模式
英文:

How to add headers info using Transport in golang net/http

问题

我正在尝试通过创建一个Transport来控制保持活动会话,以便重用TCP连接。

这是我的代码片段,我不确定如何添加身份验证的头信息。

url := "http://localhost:8181/api/v1/resource"
tr := &http.Transport{
    DisableKeepAlives:   false,
    MaxIdleConns:        0,
    MaxIdleConnsPerHost: 0,
    IdleConnTimeout:     time.Second * 10,
}
client := &http.Client{Transport: tr}
resp, err := client.Get(url)

请注意,这只是一个示例代码片段,你需要根据你的身份验证方式和需求来添加适当的头信息。

英文:

I am trying to control keep-alives session to reuse the tcp connection by creating a Trasport.

Here is my snippet and I am not sure how to add headers info for authentication.

url := "http://localhost:8181/api/v1/resource"
tr := &http.Transport{
    DisableKeepAlives:   false,
    MaxIdleConns:        0,
    MaxIdleConnsPerHost: 0,
    IdleConnTimeout:     time.Second * 10,
}
client := &http.Client{Transport: tr}
resp, err := client.Get(url)

答案1

得分: 8

这可能不是你对于你具体问题的期望结果——在你的情况下,在请求中设置更有意义,但是直接回答你的问题,你可以通过为你的传输层添加一个自定义的RoundTrip方法来为所有请求添加默认的头部。

参考:https://golang.org/pkg/net/http/#RoundTripper

类似于:

type CustomTransport struct {
  http.RoundTripper
}

func (ct *CustomTransport) RoundTrip(req *http.Request) (*http.Response, error) {
	req.Header.Add("header-key", "header-value")
	return ct.RoundTripper.RoundTrip(req)
}

url := "http://localhost:8181/api/v1/resource"
tr := &CustomTransport{
    DisableKeepAlives:   false,
    MaxIdleConns:        0,
    MaxIdleConnsPerHost: 0,
    IdleConnTimeout:     time.Second * 10,
}
client := &http.Client{Transport: tr}
resp, err := client.Get(url)

当我无法直接访问API客户端库中使用的http客户端(或每个请求对象)时,我发现这个方法很有用,但它允许我传入一个传输层。

英文:

This may not be what you want for your specific question - setting it in the request makes more sense in your case, but to answer your question directly, you should be able to add a default header to all the requests going through the transport by using a custom RoundTrip method for your Transport.

Check out https://golang.org/pkg/net/http/#RoundTripper

Something like :

type CustomTransport struct {
  http.RoundTripper
}

func (ct *CustomTransport) RoundTrip(req *http.Request) (*http.Response, error) {
	req.Header.Add("header-key", "header-value")
	return ct.RoundTripper.RoundTrip(req)
}

url := "http://localhost:8181/api/v1/resource"
tr := &CustomTransport{
    DisableKeepAlives:   false,
    MaxIdleConns:        0,
    MaxIdleConnsPerHost: 0,
    IdleConnTimeout:     time.Second * 10,
}
client := &http.Client{Transport: tr}
resp, err := client.Get(url)

I found this useful when I didn't have direct access to the http Client used by an API client library (or each request object directly), but it allowed me to pass in a transport.

答案2

得分: 3

不要混淆请求中的Client
客户端使用Transport并运行请求:client.Do(req)

您可以使用http.Request上的(h Header) Set(key, value string)设置标头:

req.Header.Set("name", "value")
英文:

Don't mix the Client from the Request.
The client uses a Transport and run the request: client.Do(req)

You set header on the http.Request with (h Header) Set(key, value string):

req.Header.Set("name", "value")

答案3

得分: 0

这是我找到的代码:

package main

import (
    "fmt"
    "io/ioutil"
    "net/http"
)

var URL = "http://httpbin.org/ip"

func main() {
    tr := &http.Transport{DisableKeepAlives: false}
    req, _ := http.NewRequest("GET", URL, nil)
    req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", "Token"))
    req.Close = false

    res, err := tr.RoundTrip(req)
    if err != nil {
        fmt.Println(err)
    }
    body, _ := ioutil.ReadAll(res.Body)
    fmt.Println(string(body))
}

它可以正常工作
英文:

This is what I found:

    package main

    import (
        "fmt"
        "io/ioutil"
        "net/http"
    )

    var URL = "http://httpbin.org/ip"

    func main() {
        tr := &http.Transport{DisableKeepAlives: false}
        req, _ := http.NewRequest("GET", URL, nil)
        req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", "Token"))
        req.Close = false

        res, err := tr.RoundTrip(req)
        if err != nil {
            fmt.Println(err)
        }
        body, _ := ioutil.ReadAll(res.Body)
        fmt.Println(string(body))
    }

And it works.

huangapple
  • 本文由 发表于 2016年12月20日 03:30:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/41229694.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定