如何在 Go 中使用不记名令牌发出请求 [英] How can I make a request with a bearer token in Go

查看:23
本文介绍了如何在 Go 中使用不记名令牌发出请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在授权请求中使用不记名令牌向 API 发出 GET 请求.我怎样才能在 Go 中做到这一点?我有以下代码,但没有成功.

包主进口 (io/ioutil"日志"网络/http")功能主(){url := "https://api.globalcode.com.br/v1/publico/eventos"响应,错误:= http.Get(url)resp.Header.Add("Bearer", "token")如果错误!= nil {log.Println("Erro ao realizar request.
[ERRO] -", err)}body, _ := ioutil.ReadAll(resp.Body)log.Println(string([]byte(body)))}

解决方案

要控制 HTTP 客户端标头、重定向策略和其他设置,请创建一个客户端:

包主进口 (io/ioutil"日志"网络/http")功能主(){网址:=https://api.globalcode.com.br/v1/publico/eventos"//通过附加字符串访问令牌创建一个承载字符串var bearer = "Bearer";+ <此处访问令牌>//使用http创建一个新请求req, err := http.NewRequest("GET", url, nil)//向请求添加授权头req.Header.Add(授权",承载)//使用 http 客户端发送请求客户端 := &http.Client{}响应,错误:= client.Do(req)如果错误!= nil {log.Println("响应错误.
[错误] -", err)}延迟 resp.Body.Close()身体,错误:= ioutil.ReadAll(resp.Body)如果错误!= nil {log.Println(读取响应字节时出错:", err)}log.Println(string([]byte(body)))}

<块引用>

客户端的传输通常具有内部状态(缓存的 TCP连接),所以客户端应该被重用而不是创建为需要.客户端对于多个 goroutine 并发使用是安全的.

Client 比 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.
[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.
[ERROR] -", err)
    }
    defer resp.Body.Close()

    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        log.Println("Error while reading the response bytes:", err)
    }
    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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆