dongnaigu2052 2018-09-10 14:42
浏览 88
已采纳

在带有Golang和Standard Env的Google App Engine上使用urlfetch添加标题的正确方法

I am newer to Go and Google App Engine and I'm trying to build a simple middleware API that queries an external API.

Because I am using the standard env on Google App Engine I have to use urlfetch to create a http request. With Google's documentation, I can't figure out how to add in headers to my GET request - though the documentation clearly states I can add in headers.

https://cloud.google.com/appengine/docs/standard/go/outbound-requests

This is the code I am trying to modify to include a custom request 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)
}

Any help would be much appreciated.

  • 写回答

1条回答 默认 最新

  • duanhan7001 2018-09-10 15:15
    关注

    Here is a working solution that uses http.NewRequest to add in a header.

    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)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵