如何在Go中使用承载令牌发出请求 [英] How can I make a request with a bearer token in Go
问题描述
我需要使用授权请求中的承载令牌向API发出GET请求.我该如何在Go中执行此操作?我有以下代码,但没有成功.
package main
import (
"io/ioutil"
"log"
"net/http"
)
func main() {
url := "https://api.globalcode.com.br/v1/publico/eventos"
resp, err := http.Get(url)
resp.Header.Add("Bearer", "token")
if err != nil {
log.Println("Erro ao realizar request.\n[ERRO] -", err)
}
body, _ := ioutil.ReadAll(resp.Body)
log.Println(string([]byte(body)))
}
要控制HTTP客户端标头,重定向策略和其他设置,请创建客户端:
package main
import (
"io/ioutil"
"log"
"net/http"
)
func main() {
url := "https://api.globalcode.com.br/v1/publico/eventos"
// Create a Bearer string by appending string access token
var bearer = "Bearer " + <ACCESS TOKEN HERE>
// Create a new request using http
req, err := http.NewRequest("GET", url, nil)
// add authorization header to the req
req.Header.Add("Authorization", bearer)
// Send req using http Client
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
log.Println("Error on response.\n[ERRO] -", err)
}
body, _ := ioutil.ReadAll(resp.Body)
log.Println(string([]byte(body)))
}
客户端的传输通常具有内部状态(缓存的TCP 连接),因此应重新使用客户端,而不是将其创建为 需要.客户端可以安全地被多个goroutine并发使用.
客户端比RoundTripper(例如Transport)的级别更高,并且 另外还处理HTTP详细信息,例如cookie和重定向.
有关客户端和传输设备的详细信息,请检查net/http软件包的golang规范 >
I need to make a GET request to an API with a bearer token in the authorization request. How can I do this in Go? I have the following code, but I haven't had success.
package main
import (
"io/ioutil"
"log"
"net/http"
)
func main() {
url := "https://api.globalcode.com.br/v1/publico/eventos"
resp, err := http.Get(url)
resp.Header.Add("Bearer", "token")
if err != nil {
log.Println("Erro ao realizar request.\n[ERRO] -", err)
}
body, _ := ioutil.ReadAll(resp.Body)
log.Println(string([]byte(body)))
}
For control over HTTP client headers, redirect policy, and other settings, create a Client:
package main
import (
"io/ioutil"
"log"
"net/http"
)
func main() {
url := "https://api.globalcode.com.br/v1/publico/eventos"
// Create a Bearer string by appending string access token
var bearer = "Bearer " + <ACCESS TOKEN HERE>
// Create a new request using http
req, err := http.NewRequest("GET", url, nil)
// add authorization header to the req
req.Header.Add("Authorization", bearer)
// Send req using http Client
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
log.Println("Error on response.\n[ERRO] -", err)
}
body, _ := ioutil.ReadAll(resp.Body)
log.Println(string([]byte(body)))
}
The Client's Transport typically has internal state (cached TCP connections), so Clients should be reused instead of created as needed. Clients are safe for concurrent use by multiple goroutines.
A Client is higher-level than a RoundTripper (such as Transport) and additionally handles HTTP details such as cookies and redirects.
For more information on Client and Transport check golang spec for net/http package
这篇关于如何在Go中使用承载令牌发出请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!