如何在Go中使用承载令牌发出请求

如何在Go中使用承载令牌发出请求

本文介绍了如何在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)))
}

有关客户端和传输设备的详细信息,请检查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)))
}

For more information on Client and Transport check golang spec for net/http package

这篇关于如何在Go中使用承载令牌发出请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 16:01