0

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

Thomson Tran
  • 180
  • 8
Lis Dya
  • 317
  • 3
  • 14

1 Answers1

1

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...)
aviraldg
  • 9,531
  • 6
  • 41
  • 56
  • Hi aviraldg and thanks for the time you took to answer my question. I did what you said and it's true that the app is deployed fine now, however, as a result, I do **not** get the JSON file with the actual direction as it supposed to get, I only get displayed [Get https://maps.googleapis.com/maps/api/directions/json?origin=&destination=&mode=&key=APIKey not an App Engine context](https://i.ibb.co/xGrtXG3/Capture.jpg). Do you have any suggestion on that? – Lis Dya Jun 20 '20 at 03:42
  • You might have to fix your main() function following: https://cloud.google.com/appengine/docs/standard/go/go-differences#writing_a_main_package – Thomson Tran Jun 25 '20 at 02:24