gpt4 book ai didi

google-app-engine - 在 Go Lang 中为整个结构设置标签

转载 作者:IT王子 更新时间:2023-10-29 00:44:20 26 4
gpt4 key购买 nike

我正在使用 Go 和 GoRestful 为存储在 Google App Engine Datastore 上的一些实体编写一个 RESTFUL 前端。

数据被转换为 JSON/XML,并通过控制每种格式样式的标签呈现给用户。我怎样才能将标签应用于结构本身的名称,以便使用正确的样式输出它?

我的结构的一个例子是:

type Shallow struct {
Key string `datastore:"-" json:"key" xml:"key"`
LastModified time.Time `json:"last_modified" xml:"last-modified"`
Version int `json:"version" xml:"version"`
Status int `json:"status" xml:"status"`
Link Link `datastore:"-" json:"link" xml:"link"`
Name string `json:"name" xml:"name"`
}

type ProbabilityEntry struct {
ItemId int64 `datastore:"ItemId" json:"item_id" xml:"item-id"`
Probability float32 `datastore:"Probability" json:"probability" xml:"probability"`
Quantity int16 `datastore:"Quantity" json:"quantity" xml:"quantity"`
}

type LootTable struct {
Shallow
AllowPreload bool `json:"allow_preload" xml:"allow-preload"`
Probabilities []ProbabilityEntry `json:"probabilities" xml:"probabilities"`
}

当 LootTable 结构发送到 JSON/XML 时,它应该将自己表示为“loot_table”或“loot-table”而不是“LootTable”。

最佳答案

简单的回答:

将它包裹在一个外部结构中:

type Payload struct {
Loot LootTable `json:"loot_table"`
}

更长的答案:

如果 JSON 的接收者知道他们得到的是什么,那么这并不是真正必要的。但是,在构建 JSON API 时,我经常创建一个 Response 结构,其中包含有关请求的额外详细信息,其中可能包括响应的类型。这是一个例子:

type JSONResponse struct {
Obj interface{} `json:"obj"` // Marshall'ed JSON (not wrapped)
Type string `json:"type"` // "loot_table" for example
Ok bool `json:"ok"` // Does this response require error handling?
Errors []string `json:"errors"` // Any errors, you could leave out Ok and just check this
}

同样,通过 API 调用,您通常知道自己期望什么,但如果响应可能是多种类型之一,则此方法会有所帮助。

关于google-app-engine - 在 Go Lang 中为整个结构设置标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20932231/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com