我正在尝试使用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.

最佳答案

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

10-07 19:12
查看更多