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

报告相同问题?

悬赏问题

  • ¥50 易语言把MYSQL数据库中的数据添加至组合框
  • ¥20 求数据集和代码#有偿答复
  • ¥15 关于下拉菜单选项关联的问题
  • ¥20 java-OJ-健康体检
  • ¥15 rs485的上拉下拉,不会对a-b<-200mv有影响吗,就是接受时,对判断逻辑0有影响吗
  • ¥15 使用phpstudy在云服务器上搭建个人网站
  • ¥15 应该如何判断含间隙的曲柄摇杆机构,轴与轴承是否发生了碰撞?
  • ¥15 vue3+express部署到nginx
  • ¥20 搭建pt1000三线制高精度测温电路
  • ¥15 使用Jdk8自带的算法,和Jdk11自带的加密结果会一样吗,不一样的话有什么解决方案,Jdk不能升级的情况