我有以下代码可以从 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 的新手,所以请耐心等待。谢谢
1 回答
catspeake
TA贡献1111条经验 获得超0个赞
如果您检查urlfetch 的 godoc,您会看到它链接到定义 Context 类型的位置。这反过来告诉你“从 Go 1.7 开始,这个包在标准库中的名称上下文中可用。https://golang.org/pkg/context。”
所以添加一个导入:
import "context"
并将其称为:
func fetchDirection(ctx context.Context, origin string...)
- 1 回答
- 0 关注
- 130 浏览
添加回答
举报
0/150
提交
取消