【问题标题】:why is GAE returning server error when the code works in the local development server?当代码在本地开发服务器中运行时,为什么 GAE 返回服务器错误?
【发布时间】:2017-12-04 04:21:39
【问题描述】:

我正在尝试使用 Google App Engine 测试 Datastore 功能,并且我的代码在本地开发服务器中按预期工作:

// code based on the following guide: https://cloud.google.com/datastore/docs/reference/libraries#client-libraries-install-go
package datastoretest

import (
        "fmt"
        "log"
        "net/http"
        "cloud.google.com/go/datastore"
        "google.golang.org/appengine" 
)

type Task struct {
        Description string
}

func init() {
    http.HandleFunc("/", handler)
}

func handler(w http.ResponseWriter, r *http.Request) {

    ctx := appengine.NewContext(r)

    // Set Google Cloud Platform project ID.
    projectID := "myProjectID" //note: actual ID is different

    // Creates a client.
    client, err := datastore.NewClient(ctx, projectID)
    if err != nil {
        log.Fatalf("Failed to create client: %v", err)
    }

    // Sets the kind for the new entity.
    kind := "Task"
    // Sets the name/ID for the new entity.
    name := "sampletask1"
    // Creates a Key instance.
    taskKey := datastore.NameKey(kind, name, nil)

    // Creates a Task instance.
    task := Task{
            Description: "Buy milk",
    }

    // Saves the new entity.
    if _, err := client.Put(ctx, taskKey, &task); err != nil {
            log.Fatalf("Failed to save task: %v", err)
    }

    fmt.Fprint(w, "Saved ", taskKey, ":", task.Description)

}

但是,在部署到 GAE 项目后,它会向访问者返回以下消息:

Error: Server Error
The server encountered an error and could not complete your request.
Please try again in 30 seconds.

【问题讨论】:

  • 错误告诉您应用程序已退出。应用程序可能由于调用 log.Fatalf 而退出。使用appengine loggger 记录错误并从处理程序返回,而不是调用 log.Fatalf。查看控制台中的错误以确定可能出现的问题。
  • 我使用了appengine logger,并删除了常规日志包,但是删除log.Fatalf并没有解决问题。看来函数 client.Put 是问题的一个原因,因为注释掉它会使网页加载正常,但为什么呢?
  • Put 返回的错误是什么?
  • 我看不到来自 Put 的具体错误。该页面一直在加载,最终日志显示“此请求导致为您的应用程序启动一个新进程,从而导致您的应用程序代码首次加载。因此,此请求可能需要更长的时间并使用更多的 CPU 比您的应用程序的典型请求。”然后它说“进程终止,因为超过了请求截止日期。(错误代码123)”
  • 我有另一个可能与此代码相关的问题:在检查 localhost:8000/datastore 的本地数据存储时,似乎该实体实际上并未被保存:“数据存储在 Empty 中没有实体命名空间。”然而,client.Put 没有产生错误,因为返回了 error = nil。

标签: google-app-engine go google-cloud-datastore


【解决方案1】:

我发现使用包“cloud.google.com/go/datastore”导致了问题。相反,该解决方案应该使用“google.golang.org/appengine/datastore”包来实现。在我的实现中,前一个包似乎与 GAE 不兼容。切换到后一个包会导致工作代码。对于 GAE 中的 Datastore,应该遵循以下更好的教程:https://cloud.google.com/appengine/docs/standard/go/getting-started/creating-guestbook

【讨论】:

  • 比什么更好的教程?如果有教程要求使用错误的库,则需要修复。
  • (该页面没有使用 appengine 包,所以尝试以这种方式调整它可能是我自己的错,但是这两个版本对我来说非常相似,有些用户甚至建议我们可以使用任一个)
猜你喜欢
  • 1970-01-01
  • 2017-01-29
  • 2018-10-04
  • 1970-01-01
  • 2015-04-21
  • 1970-01-01
  • 2021-09-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多