
本文介绍了在使用 GoRest 框架构建 API 时,如何修改输出数据的 JSON 结构,使其包含一个顶层的对象 ID,以满足前端模板引擎(如 Mustache.js)的需求。通过修改数据结构和 EndPoint 的 output 定义,可以轻松实现所需的 JSON 格式。
在使用 GoRest 构建 API 时,有时我们需要调整 API 返回的 JSON 数据的结构,以便更好地与前端模板引擎或其他客户端进行交互。例如,某些模板引擎可能期望 JSON 数据包含一个顶层对象 ID,而不是直接返回一个数组。
以下是如何修改 GoRest API 的输出,以提供包含对象 ID 的 JSON 数据的方法:
1. 修改数据结构
首先,我们需要创建一个新的数据结构,该结构将包含一个字段用于存储原始数据数组。例如,如果原始数据是一个 Item 类型的数组,我们可以创建一个名为 ItemStore 的结构体,其中包含一个 Items 字段,该字段是一个 Item 类型的切片。
type ItemStore struct {
Items []Item `json:"repo"` // 修改json tag
}
type Item struct {
Id int `json:"Id"`
FileName string `json:"FileName"`
Active bool `json:"Active"`
}
var itemStore ItemStore在这个例子中,我们添加了 json:"repo" tag,这样JSON序列化后的key会变成repo。
2. 修改 EndPoint 的 output 定义
接下来,我们需要修改 GoRest EndPoint 的 output 定义,将其指向新的数据结构 ItemStore,而不是原始的 []Item。
Android文档-开发者指南-第一部分:入门-中英文对照版 Android提供了丰富的应用程序框架,它允许您在Java语言环境中构建移动设备的创新应用程序和游戏。在左侧导航中列出的文档提供了有关如何使用Android的各种API来构建应用程序的详细信息。第一部分:Introduction(入门) 0、Introduction to Android(引进到Android) 1、Application Fundamentals(应用程序基础) 2、Device Compatibility(设备兼容性) 3、
11
type HelloService struct {
gorest.RestService `root:"/api" consumes:"application/json" produces:"application/json"`
playList gorest.EndPoint `method:"GET" path:"/list/" output:"ItemStore"`
playItem gorest.EndPoint `method:"PUT" path:"/go/{Id:int}" postdata:"Item"`
}
func (serv HelloService) PlayList() ItemStore {
serv.ResponseBuilder().SetResponseCode(200)
// 假设 itemStore.Items 已经填充了数据
return itemStore
}3. 返回新的数据结构
最后,在处理请求的函数中,我们需要返回新的 ItemStore 结构体,而不是原始的 []Item 切片。
完整示例
package main
import (
"github.com/gorilla/mux"
"github.com/gorilla/handlers"
"github.com/emicklei/go-restful/v3"
"log"
"net/http"
"os"
)
type HelloService struct {
restful.WebService
}
func NewHelloService() *HelloService {
s := new(HelloService)
s.
WebService = restful.WebService{}
s.
Path("/api").
Consumes(restful.MIME_JSON).
Produces(restful.MIME_JSON)
s.Route(s.GET("/list").To(s.PlayList).Produces(restful.MIME_JSON).Writes(ItemStore{}))
s.Route(s.PUT("/go/{Id}").To(s.PlayItem).Consumes(restful.MIME_JSON).Reads(Item{}))
return s
}
func (serv *HelloService) PlayList(request *restful.Request, response *restful.Response) {
response.WriteHeader(http.StatusOK)
response.WriteEntity(itemStore)
}
func (serv *HelloService) PlayItem(request *restful.Request, response *restful.Response) {
id := request.PathParameter("Id")
var item Item
err := request.ReadEntity(&item)
if err != nil {
response.WriteHeader(http.StatusBadRequest)
return
}
log.Printf("Received item: %+v with ID: %s\n", item, id)
response.WriteHeader(http.StatusOK)
}
type ItemStore struct {
Items []Item `json:"repo"`
}
type Item struct {
Id int `json:"Id"`
FileName string `json:"FileName"`
Active bool `json:"Active"`
}
var itemStore ItemStore
func main() {
itemStore = ItemStore{
Items: []Item{
{Id: 1, FileName: "test :1", Active: false},
{Id: 2, FileName: "test :2", Active: false},
},
}
wsContainer := restful.NewContainer()
NewHelloService().AddToWebService(wsContainer)
// Optionally, you can enable logging.
accessLog := log.New(os.Stdout, "api-access ", log.LstdFlags)
cors := handlers.CORS(
handlers.AllowedHeaders([]string{"Content-Type", "Accept"}),
handlers.AllowedOrigins([]string{"*"}),
handlers.AllowedMethods([]string{"GET", "POST", "PUT", "DELETE", "OPTIONS"}),
)
router := mux.NewRouter()
router.PathPrefix("/").Handler(wsContainer)
loggedRouter := handlers.CombinedLoggingHandler(os.Stdout, router)
preflightRouter := cors(loggedRouter)
log.Printf("start listening on localhost:8080")
server := &http.Server{Addr: ":8080", Handler: preflightRouter}
log.Fatal(server.ListenAndServe())
}注意事项
总结
通过修改数据结构和 GoRest EndPoint 的 output 定义,我们可以轻松地控制 API 返回的 JSON 数据的结构,使其满足前端或其他客户端的需求。这种方法可以帮助我们更好地与各种不同的系统进行集成,并提高 API 的灵活性和可用性。
以上就是使用 GoRest 构建 API 时如何提供 JSON 对象 ID的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号