Home > Net >  How can I get http header in Go?
How can I get http header in Go?

Time:06-29

I use Postman to get some information from the cloud platform API. First, I need to get a token and after that, I need to use this token for other API requests. The name of this token is x-vmware-vcloud-access-token How can I get the HTTP token in the right way in Go? I need to save it to a variable and use it for other requests. The code below was generated by Postman.

 func getToken() {
    url := "https://some-ip-address-here.com/sessions"
    method := "POST"

    client := &http.Client{}
    req, err := http.NewRequest(method, url, nil)

    if err != nil {
        fmt.Println(err)
        return
    }
    req.Header.Add("Accept", "application/* xml;version=35.0")
    req.Header.Add("Authorization", "Basic ABCDEFGHIJKLMN123")
    res, err := client.Do(req)
    if err != nil {
        fmt.Println(err)
        return
    }
    defer res.Body.Close()

    if err != nil {
        fmt.Println(err)
        return
    }
}

CodePudding user response:

If you have a request of type http.Request then you can use the following to extract header from request.

accessToken := req.Header.Get("x-vmware-vcloud-access-token")
  •  Tags:  
  • go
  • Related