使用Golang和标准环境在Google App Engine上使用urlfetch添加标题的正确方法

3
我刚开始接触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)
}

任何帮助都将不胜感激。

urfletch.Client 返回一个 http.Client,因此您应该能够使用 http.NewRequest 创建请求,像在任何其他 Go 应用程序中一样添加标头,然后使用 urlfetch.Client 返回的客户端的 Do 方法执行请求。如何在请求对象上设置标头在 这个问题 中有所回答。 - Leon
1个回答

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)
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接