我是 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)
}
- 1 回答
- 0 關注
- 139 瀏覽
添加回答
舉報
0/150
提交
取消