從golang-gin-realworld-example-app項目學寫httpapi (三)

https://github.com/gothinkster/golang-gin-realworld-example-app/blob/master/users/serializers.gogit

序列化定義

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
}
相關文章
相關標籤/搜索