我是Go和Google App Engine的新手,我正在尝试构建一个查询外部API的简单中间件API。
由于我在Google App Engine上使用标准环境,因此必须使用urlfetch创建一个http请求。借助Google的文档,我无法弄清楚如何在GET请求中添加标头-尽管文档明确指出可以添加标头。
https://cloud.google.com/appengine/docs/standard/go/outbound-requests
这是我要修改的代码,以包括自定义请求标头:
import (
"fmt"
"net/http"
"google.golang.org/appengine"
"google.golang.org/appengine/urlfetch"
)
func handler(w http.ResponseWriter, r *http.Request) {
ctx := appengine.NewContext(r)
client := urlfetch.Client(ctx)
resp, err := client.Get("https://www.google.com/")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
fmt.Fprintf(w, "HTTP GET returned status %v", resp.Status)
}
任何帮助将不胜感激。
答案 0 :(得分:3)
这是使用http.NewRequest
来添加标题的有效解决方案。
func handler(w http.ResponseWriter, r *http.Request) {
ctx := appengine.NewContext(r)
client := urlfetch.Client(ctx)
req, err := http.NewRequest("GET", "https://www.google.com/", nil)
req.Header.Add("CUSTOM-HEADER", "VALUE")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
resp, err := client.Do(req)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
fmt.Fprintf(w, "HTTP GET returned status %v", resp.Status)
}