首页 > 解决方案 > 在带有 Golang 和 Standard Env 的 Google App Engine 上使用 urlfetch 添加标头的正确方法

问题描述

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

任何帮助将非常感激。

标签: google-app-enginego

解决方案


这是一个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)
}

推荐阅读