亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用 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 關注
  • 139 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號