为了账号安全,请及时绑定邮箱和手机立即绑定

使用 Golang 和 Standard Env 在 Google App Engine 上使用

使用 Golang 和 Standard Env 在 Google App Engine 上使用

Go
哈士奇WWW 2023-04-04 14:12:01
我是 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)}任何帮助将非常感激。
查看完整描述

1 回答

?
慕森卡

TA贡献1806条经验 获得超8个赞

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

}


查看完整回答
反对 回复 2023-04-04
  • 1 回答
  • 0 关注
  • 94 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信