gogoogle-cloud-platformgoogle-app-engine-golang

How to use Context when getting a direction with GO?


I'm having the following code to get the direction from Google Cloud:

import (
    "google.golang.org/appengine"
    "google.golang.org/appengine/urlfetch"
    "fmt"
    "io/ioutil"
    "net/http"
)

const directionAPIKey = "APIKey"
const directionURL = "https://maps.googleapis.com/maps/api/directions/json?origin=%s&destination=%s&mode=%s&key=%s"

func main() {
    http.HandleFunc("/", handler)
}

func handler(w http.ResponseWriter, r *http.Request) {
    ctx := appengine.NewContext(r)
    direction, err := fetchDirection(ctx, r.FormValue("origin"), r.FormValue("destination"), r.FormValue("mode"))
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }
    w.Header().Add("Content-Type", "application/json; charset=utf-8")
    w.Write(direction)
}

func fetchDirection(ctx appengine.Context, origin string, destination string, mode string) ([]byte, error) {
    client := urlfetch.Client(ctx)
    resp, err := client.Get(fmt.Sprintf(directionURL, origin, destination, mode, directionAPIKey))
    if err != nil {
        return nil, err
    }
    defer resp.Body.Close()
    return ioutil.ReadAll(resp.Body)
}

But I get an error:

undefined: appengine.Context

When trying to deploy the app. What I have tried is to change:

ctx := appengine.NewContext(r)

into

ctx := r.Context()

And

func fetchDirection(ctx appengine.Context, origin string...)

into

func fetchDirection(ctx Context, origin string...)

But I get:

undefined: Context

I'm completely lost. I'm new to Go and GCP, so please be patient with me. Thanks


Solution

  • If you check the godoc for urlfetch you'll see it links to where the Context type is defined. That in turn tells you that "As of Go 1.7 this package is available in the standard library under the name context. https://golang.org/pkg/context."

    So add an import:

    import "context"
    

    and refer to it as:

    func fetchDirection(ctx context.Context, origin string...)