如何使用google/jsonapi输出带分页链接的JSON:API响应?
使用google/jsonapi输出分页链接的正确方式
你遇到的报错是因为jsonapi.MarshalPayload仅支持接收结构体指针或结构体切片指针作为参数,直接传map[string]interface{}不符合要求。以下是两种实现顶层分页链接的有效方案:
方案1:使用MarshalPayloadWithLinks(推荐)
google/jsonapi提供了MarshalPayloadWithLinks函数,专门用于在顶层输出links字段,无需额外定义结构体:
// 设置响应Content-Type c.Response().Header().Set(echo.HeaderContentType, jsonapi.MediaType) // 定义分页链接 topLinks := jsonapi.Links{ "self": "http://example.com/users", "next": "http://example.com/users?page[offset]=2", "last": "http://example.com/users?page[offset]=10", } // 序列化数据并附带顶层链接 err = jsonapi.MarshalPayloadWithLinks(c.Response(), users, topLinks) if err != nil { return echo.ErrInternalServerError }
方案2:自定义顶层结构体并实现Linkable接口
如果需要更灵活的顶层元数据控制,可以定义一个包含数据的结构体,并实现jsonapi.Linkable接口来返回顶层链接:
// 定义顶层响应结构体 type UserListResponse struct { Data []*User `jsonapi:"data"` } // 实现Linkable接口,返回顶层链接 func (resp *UserListResponse) JSONAPILinks() *jsonapi.Links { return &jsonapi.Links{ "self": "http://example.com/users", "next": "http://example.com/users?page[offset]=2", "last": "http://example.com/users?page[offset]=10", } } // 序列化响应 c.Response().Header().Set(echo.HeaderContentType, jsonapi.MediaType) resp := &UserListResponse{Data: users} err = jsonapi.MarshalPayload(c.Response(), resp) if err != nil { return echo.ErrInternalServerError }
以上两种方案都能输出符合JSON:API规范的响应结构,即顶层包含links和data字段,和你期望的格式一致。
内容的提问来源于stack exchange,提问作者JSP
相关产品推荐
相关产品推荐

