在 Go 中添加默认 HTTP 标头
时间:2024-04-16
浏览:200
作者:佚名
来到golang学习网的大家,相信都是编程学习爱好者,希望在这里学习Golang相关编程知识。下面本篇文章就来带大家聊聊《在 Go 中添加默认 HTTP 标头》,介绍一下,希望对大家的知识积累有所帮助,助力实战开发!
问题内容
我正在迈出 go 的第一步,并且想要使用 rest api。服务器要求每个请求都使用不记名令牌进行授权。
如何将此标头添加到客户端以便每个请求都使用此令牌?
import "net/http"
const accessToken = "MY_DEMO_TOKEN"
func main() {
customHeader := http.Header{}
customHeader.Add("Authorization: Bearer %s", accessToken)
client := &http.Client{
Timeout: time.Second*10,
}
}解决方案
您可以装饰客户端的交通工具。例如:
package main
import "net/http"
func main() {
client := http.defaultclient
rt := withheader(client.transport)
rt.set("authorization", "bearer <token>")
client.transport = rt
client.get("http://example.com")
}
type withheader struct {
http.header
rt http.roundtripper
}
func withheader(rt http.roundtripper) withheader {
if rt == nil {
rt = http.defaulttransport
}
return withheader{header: make(http.header), rt: rt}
}
func (h withheader) roundtrip(req *http.request) (*http.response, error) {
if len(h.header) == 0 {
return h.rt.roundtrip(req)
}
req = req.clone(req.context())
for k, v := range h.header {
req.header[k] = v
}
return h.rt.roundtrip(req)
}
对于授权令牌的特定用途,您可能对 golang.org/x/oauth2 软件包感兴趣,它的功能基本相同,但也支持自动令牌续订:
package main
import (
"context"
"golang.org/x/oauth2"
)
func main() {
ctx := context.Background()
client := oauth2.NewClient(ctx, oauth2.StaticTokenSource(&oauth2.Token{
AccessToken: "<your token>",
TokenType: "Bearer",
}))
client.Get("http://example.com")
}以上就是《在 Go 中添加默认 HTTP 标头》的详细内容,更多关于的资料请关注golang学习网公众号!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
11.15
站内热门
最新文章
11.20
11.20
11.20
11.20
热门专题
