我是 Go 和 Google App Engine 的新手,我正在尝试构建一个查询外部 API 的简单中间件 API。
因为我在 Google App Engine 上使用标准环境,所以我必须使用 urlfetch 来创建 http 请求。使用 Google 的文档,我无法弄清楚如何将 header 添加到我的 GET 请求中 - 尽管该文档明确指出我可以添加 header 。
https://cloud.google.com/appengine/docs/standard/go/outbound-requests
这是我试图修改以包含自定义请求 header 的代码:
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)
}
如有任何帮助,我们将不胜感激。
最佳答案
这是一个使用 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)
}
关于google-app-engine - 使用 Golang 和 Standard Env 在 Google App Engine 上使用 urlfetch 添加 header 的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52260298/