我有以下代码可以从 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)
}
但我收到一个错误:
未定义:appengine.Context
尝试部署应用程序时。我尝试过的是改变:
ctx := appengine.NewContext(r)
进入
ctx := r.Context()
和
func fetchDirection(ctx appengine.Context, origin string...)
进入
func fetchDirection(ctx Context, origin string...)
但我得到:
undefined: Context
我完全迷路了。我是 Go 和 GCP 的新手,所以请耐心等待。谢谢