
在使用 Google App Engine (GAE) 数据存储时,经常会遇到需要自动生成唯一标识符的需求。然而,开发者在使用 Go 语言与数据存储交互时,可能会发现实体对象的 ID 字段始终为零,即使数据已经成功存储。这并非 GAE 自动填充 ID 字段,而是需要开发者手动从 datastore.Put 操作返回的键中提取。本文将详细介绍如何正确地获取和使用 GAE 数据存储生成的唯一 ID,并探讨手动生成 ID 的方法。
App Engine 的数据存储不会自动修改你的 Go 结构体,并自动填充 ID 字段。当你使用 datastore.NewIncompleteKey 创建一个不完整的键,并将其传递给 datastore.Put 函数时,数据存储会生成一个唯一的数字 ID。这个 ID 包含在 datastore.Put 返回的键中,你需要从这个键中提取 ID 并将其设置到你的结构体中。
以下代码展示了如何从 datastore.Put 返回的键中获取生成的 ID,并更新 Participant 结构体:
package main
import (
"context"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"google.golang.org/appengine/datastore"
)
type Participant struct {
ID int64
LastName string
FirstName string
Birthdate string
Email string
Cell string
}
func serveError(c context.Context, w http.ResponseWriter, err error) {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
func handleParticipant(c context.Context, w http.ResponseWriter, r *http.Request) {
switch r.Method {
case "POST":
d, _ := ioutil.ReadAll(r.Body)
participant := new(Participant)
err := json.Unmarshal(d, &participant)
if err != nil {
serveError(c, w, err)
return
}
var key *datastore.Key
parentKey := datastore.NewKey(c, "Parent", "default_parent", 0, nil) // 替换为你的父键
if participant.ID == 0 {
// no id yet .. create an incomplete key and allow the db to create one.
key = datastore.NewIncompleteKey(c, "participant", parentKey)
} else {
// we have an id. use that to update
key = datastore.NewKey(c, "participant", "", participant.ID, parentKey)
}
// PERSIST!
putKey, e := datastore.Put(c, key, participant)
if e != nil {
serveError(c, w, e)
return
}
// ** 获取生成的 ID 并更新 participant 结构体 **
participant.ID = putKey.IntID()
// Fetch back out of the database, presumably with my new ID
if e = datastore.Get(c, putKey, participant); e != nil {
serveError(c, w, e)
return
}
// send to the consumer
jsonBytes, _ := json.Marshal(participant)
w.Write(jsonBytes)
default:
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
}
}
func main() {
http.HandleFunc("/participant", func(w http.ResponseWriter, r *http.Request) {
// 在 App Engine 环境中,你可以直接使用 context.Background()
// 但在本地开发环境中,你需要使用 appengine.NewContext(r)
// 这里为了兼容性,我们使用 context.Background()
ctx := context.Background()
handleParticipant(ctx, w, r)
})
fmt.Println("Server listening on port 8080")
http.ListenAndServe(":8080", nil)
}
代码解释:
如果你不想依赖 App Engine 自动生成 ID,也可以选择手动生成唯一 ID。这通常涉及到使用 UUID (Universally Unique Identifier) 或其他唯一性算法。
import (
"github.com/google/uuid"
)
func generateUUID() string {
id, _ := uuid.NewUUID()
return id.String()
}
// ... 在你的 Participant 结构体中使用 string 类型的 ID
type Participant struct {
ID string
LastName string
FirstName string
Birthdate string
Email string
Cell string
}
// ... 在创建新 Participant 时生成 UUID
participant.ID = generateUUID()
key = datastore.NewKey(c, "participant", participant.ID, 0, parentKey) // 使用字符串 ID 作为键名注意事项:
在 Go 语言中,每个类型都有一个零值。对于 int64 类型,零值是 0。这就是为什么在你的原始代码中,participant.ID 始终为 0,因为你没有显式地设置它。
关于字符串的零值,指的是空字符串 ""。当你看到文档中提到 "string 可以是零值" 时,指的是它可以是空字符串。
在使用 Google App Engine 数据存储时,理解 ID 生成机制至关重要。App Engine 不会自动填充结构体中的 ID 字段,你需要手动从 datastore.Put 返回的键中提取 ID。或者,你可以选择手动生成唯一 ID。 掌握这些概念将帮助你更有效地使用 Go 语言与 App Engine 数据存储进行交互。
以上就是Go App Engine 数据存储:生成唯一标识符的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号