1 Star 0 Fork 0

肖金光 / goclean

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
model.go 3.04 KB
一键复制 编辑 原始数据 按行查看 历史
xiaojg-mbp 提交于 2024-03-07 16:51 . go11day08.02补充 RESTful SDK
package blog
import (
"encoding/json"
"time"
"gitee.com/aviptle/goclean/go11jin/vblog01/common"
)
func NewBlogSet() *BlogSet {
return &BlogSet{
Items: []*Blog{},
}
}
type BlogSet struct {
// 总共多个篇文章
Total int64 `json:"total"`
Items []*Blog `json:"items"`
}
// Stringer
func (s *BlogSet) String() string {
dj, _ := json.MarshalIndent(s, "", " ")
return string(dj)
}
// 通过一个构建函数来构建Blog
// 为什么要使用构建函数?为什么不直接使用struct
// 使用构造好按时保证兼容性: 把需要初始化的 在这个函数进行初始化,
// 有需要默认执行,补充默认值
func NewBlog(req *CreateBlogRequest) *Blog {
return &Blog{
Meta: NewMeta(),
CreateBlogRequest: req,
}
}
// 数据
// 这个对象如何保存数据库里面 ?
// 通过匿名嵌套来组合产生新的结构体
type Blog struct {
*Meta
*CreateBlogRequest
}
// type Tabler interface {
// TableName() string
// }
//
// 定义gorm 存入数据时表的名称
func (i *Blog) TableName() string {
return "blogs"
}
// Stringer
func (s *Blog) String() string {
dj, _ := json.MarshalIndent(s, "", " ")
return string(dj)
}
func NewMeta() *Meta {
return &Meta{
CreatedAt: time.Now().Unix(),
}
}
// 文章的元数据:
// + 文章的Id
// + 创建时间
// + 修改时间
// + 发布时间
type Meta struct {
Id int `json:"id"`
// 直接用时间戳, 我选择用时间戳
// 我们是做后端, 一般数据库的时间对象是又时区约束
// 后端直接存储时间戳, 当需要展示的时候,由前端(Web,APP,...)负责带上用户的当前时区做展示
CreatedAt int64 `json:"created_at"`
UpdatedAt int64 `json:"updated_at"`
PublishedAt int64 `json:"published_at"`
}
func NewCreateBlogRequest() *CreateBlogRequest {
return &CreateBlogRequest{
Tags: map[string]string{},
Status: STATUS_DRAFT,
}
}
// 用户传入的数据
// + 标题
// + 作者
// + 内容(Markdown)
// + 标签(map)
// GORM Object ---> Table Row
// Object struct Tag: gorm:"column:title"
// 你不定义tag,默认使用你json的tag
// Insert (title) VALUE (?)
type CreateBlogRequest struct {
// CreateAt --> createAt
// CreateAt --> create_at(通常我们json的tag也是采用蛇形缩写)
// json, gorm, text
// 文章标题
Title string `json:"title" gorm:"column:title" validate:"required"`
Author string `json:"author" gorm:"column:author" validate:"required"`
Content string `json:"content" validate:"required"`
// map[string]string orm是不知道如何入库的
// 直接存成json
Tags map[string]string `json:"tags" gorm:"serializer:json"`
// 文章是由状态
Status STATUS `json:"status"`
// 新加了一个字段
// Extra map[string]string
}
// 检查用户提交的参数是否合法
// 使用这个来做校验: https://github.com/go-playground/validator
func (req *CreateBlogRequest) Validate() error {
// if req.Title == "" {
// return fmt.Errorf("title not nil")
// }
// 这个也是一个全局 对象: 校验器
// 校验规则通过写struct tag来进定义
return common.Validate(req)
}
Go
1
https://gitee.com/aviptle/goclean.git
git@gitee.com:aviptle/goclean.git
aviptle
goclean
goclean
6b9efd2ceda8

搜索帮助