簡體   English   中英

代碼顯示 URL 而不是請求 GCP 的響應與 Go

[英]Code displaying an URL rather than the reponse of the request GCP with Go

我很難在 Google Cloud Platform 中顯示方向請求的結果。 這是我嘗試過的:

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)
}

我成功部署了我的應用程序,但是,上面代碼的結果是:

Get https://maps.googleapis.com/maps/api/directions/json?origin=&destination=&mode=&key=APIKey not an App Engine context

而不是請求的結果。 這是來自瀏覽器的圖像 我怎樣才能得到想要的結果,而不僅僅是 URL? 提前致謝。

發現當您的 AppEngine 應用程序將運行時設置為 go111 並且應用程序導入任何“google.golang.org/appengine”包但應用程序不調用“ appengine.Main”

method func main() {
    http.HandleFunc("/", handler)
    appengine.Main()
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM