我在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,
}
}
答案 0 :(得分:3)
您可以装饰客户的运输工具。例如:
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) {
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")
}
答案 1 :(得分:2)
您可以围绕http.RoundTripper编写装饰器,并将其传递给客户端。但是实际上,我最终会得到一个助手,该助手根据Adrian的建议为每个查询准备请求。
package main
import (
"fmt"
"net/http"
"time"
)
const accessToken = "MY_DEMO_TOKEN"
type MyRoundTripper struct {
r http.RoundTripper
}
func (mrt MyRoundTripper) RoundTrip(r *http.Request) (*http.Response, error) {
r.Header.Add("Authorization", "Bearer: "+accessToken)
return mrt.r.RoundTrip(r)
}
func main() {
client := &http.Client{
Timeout: time.Second * 10,
Transport: MyRoundTripper{r: http.DefaultTransport},
}
fmt.Println(client.Get("http://google.com/"))
}