google-app-engine - 使用 Golang 和 Standard Env 在 Google App Engine 上使用 urlfetch 添加 header 的正确方法

标签 google-app-engine go

我是 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/

相关文章:

Java jinja/django 类 html 模板

python - 在 virtualenv 中使用 dev_appserver.py 时导入错误

python - 无法在 gae 中运行简单的 helloworld (python 2.7)

go - 调用方法表达式时没有足够的参数

docker - golang、docker、gradle的项目结构

node.js - Redis:按分数排序的集合的交集

google-app-engine - AppenginePlugin在Mac上的IntelliJ中导入gradle项目时不支持major.minor 51版错误

去获取不下载到 SRC 文件夹

go - 是否有查找完整文件权限的功能?

golang exec Output() 卡住了,但是 Run() 没问题