google-app-engine - 在带有 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)
}
任何帮助将非常感激。
解决方案
这是一个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)
}
推荐阅读
- yocto - Is there a command to got to WORDIR of a recipe?
- php - 设置 cookie 在 wordpress 中的路径有问题
- java - Oauth2.0中如何使用refresh_token重新生成access_token
- algolia - 在 Magento 2 的 Algoliya 中添加砌体视图
- python - 网络抓取最常见的名字
- powershell - 使用 PowerShell 对大量文件设置文件权限
- javascript - 有没有办法在我们自己的服务器上部署 GSuite 应用程序并在 GSuite 市场上运行?让每个人都可以使用它
- javascript - Bootstrap-star-rating 插件 - 事件被多次调用
- c++ - scanf中是否有保证的分配顺序?
- angular - 在 ag-grid 中的 gridActions 中设置 Id