https://github.com/gothinkster/golang-gin-realworld-example-app/blob/master/users/serializers.go
序列化定义
package users
import (
"gopkg.in/gin-gonic/gin.v1"
"github.com/wangzitian0/golang-gin-starter-kit/common"
)
// 用户简介序列化结构体
type ProfileSerializer struct {
C *gin.Context
UserModel
}
// 用户简介响应json结构体
type ProfileResponse struct {
ID uint `json:"-"`
Username string `json:"username"`
Bio string `json:"bio"`
Image *string `json:"image"`
Following bool `json:"following"`
}
// 用户简介的内置方法Response
func (self *ProfileSerializer) Response() ProfileResponse {
//中间件请求c.MustGet
myUserModel := self.C.MustGet("my_user_model").(UserModel)
profile := ProfileResponse{
ID: self.ID,
Username: self.Username,
Bio: self.Bio,
Image: self.Image,
Following: myUserModel.isFollowing(self.UserModel),
}
return profile
}
// 用户信息结构体
type UserSerializer struct {
c *gin.Context
}
// 用户信息响应json结构体
type UserResponse struct {
Username string `json:"username"`
Email string `json:"email"`
Bio string `json:"bio"`
Image *string `json:"image"`
Token string `json:"token"`
}
// 用户信息的内置方法Response
func (self *UserSerializer) Response() UserResponse {
//中间件请求c.MustGet
myUserModel := self.c.MustGet("my_user_model").(UserModel)
user := UserResponse{
Username: myUserModel.Username,
Email: myUserModel.Email,
Bio: myUserModel.Bio,
Image: myUserModel.Image,
Token: common.GenToken(myUserModel.ID),
}
return user
}