3

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.

Will K.
  • 77
  • 1
  • 1
  • 8
  • `urfletch.Client` returns an [`http.Client`](https://golang.org/pkg/net/http/#Client), so you should be able to use [`http.NewRequest`](https://golang.org/pkg/net/http/#NewRequest) to create your requests, add headers as you would in any other go application and then execute the request using the [`Do`](https://golang.org/pkg/net/http/#Client.Do) method of the client returned by `urlfetch.Client`. How to set headers on the request object is answered in [this question](https://stackoverflow.com/questions/12864302/how-to-set-headers-in-http-get-request). – Leon Sep 10 '18 at 15:05

1 Answers1

3

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)
}
Leon
  • 2,926
  • 1
  • 25
  • 34
Will K.
  • 77
  • 1
  • 1
  • 8