I'm having hard times trying to display the result of a direction request in Google Cloud Platform. This is what I have tried:
package main
import (
"fmt"
"net/http"
"context"
"io/ioutil"
"google.golang.org/appengine"
"google.golang.org/appengine/urlfetch"
)
const directionAPIKey = "MyAppKey"
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 context.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)
}
I got my app successfully deployed, however, the result of the above code is:
Get https://maps.googleapis.com/maps/api/directions/json?origin=&destination=&mode=&key=APIKey not an App Engine context
Rather than the result of the request. This is an image from the browser. How can I get the desired result and not only that URL? Thanks in advance.
I found that the issue "not an App Engine context" is returned when your AppEngine application has the runtime set to go111 and the application imports any of the "google.golang.org/appengine" packages but the application doesn’t call the “appengine.Main”
method func main() {
http.HandleFunc("/", handler)
appengine.Main()
}