向GET请求添加HTTP头部

huangapple go评论93阅读模式
英文:

Adding HTTP Headers to a GET request

问题

我正在创建一个使用Golang的反向代理,并且在尝试获取关于如何向API调用添加HTTP头的在线示例时遇到了问题。

这是我的API调用代码:

package handlers

import (
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
)

func (s *Server) getApiCall(w http.ResponseWriter, r *http.Request) {
	resp, err := http.Get("https://url.com")
	if err != nil {
		log.Fatalln(err)
	}
	// 在下面的代码中读取响应体
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		log.Fatalln(err)
	}
	// 将响应体转换为字符串类型
	sb := string(body)
	log.Printf(sb)
	fmt.Fprintf(w, sb)
}

在我的函数中,我应该在哪里添加一个带有Authorization头和Bearer <TOKEN>值的代码?

我对Go还不太熟悉,据我理解,这段代码应该足够了,但如果您需要更多关于我的后端的详细信息,请在需要澄清的地方添加注释。

英文:

I'm creating a reverse proxy in Golang and I'm having trouble trying to grab online examples on how to add HTTP headers to an API call.

Here is my API call:

package handlers

import (
	&quot;fmt&quot;
	&quot;io/ioutil&quot;
	&quot;log&quot;
	&quot;net/http&quot;
)


func (s *Server) getApiCall(w http.ResponseWriter, r *http.Request) {
	resp, err := http.Get(&quot;https://url.com&quot;)
	if err != nil {
		log.Fatalln(err)
	}
	//We Read the response body on the line below.
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		log.Fatalln(err)
	}
	//Convert the body to type string
	sb := string(body)
	log.Printf(sb)
	fmt.Fprintf(w, sb)
}

Where in my function can I add an Authorization header with the a Bearer &lt;TOKEN&gt; as its value?

I'm new with Go, to my understanding this should be enough code, but if you need more detail about my backend just add a comment in what needs clarification.

答案1

得分: 2

你不能使用http.Get,而是要使用http.NewRequest来创建一个请求对象,然后将头部信息添加到其中。

以下是一个示例:

client := &http.Client{}

req, err := http.NewRequest("GET", "https://url.com", nil)
if err != nil {
    // 处理错误
}

req.Header.Add("Authorization", "Bearer ...")
resp, err := client.Do(req)
if err != nil {
    // 处理错误
}

要了解更多详细信息,请参阅http package文档

英文:

You can't use http.Get, instead use http.NewRequest to create a request object then add the headers to it.

One example:

client := &amp;http.Client{}

req, err := http.NewRequest(&quot;GET&quot;, &quot;https://url.com&quot;, nil)
if err != nil {
    // handle error
}

req.Header.Add(&quot;Authorization&quot;, &quot;Bearer ...&quot;)
resp, err := client.Do(req)
if err != nil {
    // handle error
}

For more details take a look at http package doc.

huangapple
  • 本文由 发表于 2022年2月1日 02:13:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/70930836.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定