How to add header information using Transport in golang net / http

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

Here is my snippet, and I'm not sure how to add header information 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)
+4
source share
2 answers

Do not mix Client from request.
The client uses Transport and launches the request:client.Do(req)

You set the title to http.Requestwith (h Header) Set(key, value string):

req.Header.Set("name", "value")
+3
source

Here 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.

0
source

Source: https://habr.com/ru/post/1664210/


All Articles