go - 显示 URL 而非 Go 请求 GCP 响应的代码
问题描述
我很难在 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”</p>
method func main() {
http.HandleFunc("/", handler)
appengine.Main()
}
推荐阅读
- regex - 正则表达式 - 阻止 url 中的空格
- java - 从 XML 中提取属性值
- java - gradle:没有源任务':processTestResources'和':processtResources'
- swiftui-navigationlink - 后退按钮跳过 View1 -> View2 -> View3 NavigationLink 中的视图
- json - 如何使用 NLP 从条件语句中提取规则?
- swift - 无法在 swift 中为 tableview 单元格图像添加 Tapgesture
- google-maps - Google Maps JS API - 根据缩放级别调整所有自定义标记的大小
- vue.js - Vue 强制组件在可见之前渲染到 DOM
- python - 有没有办法将多对多对象关系变成字典?
- react-native - 屏幕更改时标签栏图标未完全居中