当代码在本地开发服务器中工作时,为什么GAE返回服务器错误?

时间:2017-12-04 04:21:40

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

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

// 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.

1 个答案:

答案 0 :(得分:1)

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