[英]How to use Context when getting a direction with GO?
我有以下代碼可以從 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 的新手,所以請耐心等待。 謝謝
如果您檢查urlfetch 的 godoc,您會看到它鏈接到定義 Context 類型的位置。 這反過來告訴您“從 Go 1.7 起,此 package 在名稱上下文中的標准庫中可用。https.” ://golang.org .
所以添加一個導入:
import "context"
並將其稱為:
func fetchDirection(ctx context.Context, origin string...)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.