在带有Golang和Standard Env的Google App Engine上使用urlfetch添加标题的正确方法
I am newer to Go and Google App Engine and I'm trying to build a simple middleware API that queries an external API.
Because I am using the standard env on Google App Engine I have to use urlfetch to create a http request. With Google's documentation, I can't figure out how to add in headers to my GET request - though the documentation clearly states I can add in headers.
https://cloud.google.com/appengine/docs/standard/go/outbound-requests
This is the code I am trying to modify to include a custom request 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)
}
Any help would be much appreciated.
我是Go和Google App Engine的新手,我正在尝试构建一个简单的中间件API,以查询外部 API。 p>
由于我在Google App Engine上使用标准环境,因此必须使用urlfetch创建一个http请求。 使用Google的文档,我无法弄清楚如何在GET请求中添加标头-尽管文档中明确指出可以在标头中添加标头。 p>
Here is a working solution that uses http.NewRequest
to add in a header.
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)
}