Files
assetx/webapp-back/articles/validators.go
default 2ee4553b71 init: 初始化 AssetX 项目仓库
包含 webapp(Next.js 用户端)、webapp-back(Go 后端)、
antdesign(管理后台)、landingpage(营销落地页)、
数据库 SQL 和配置文件。
2026-03-27 11:26:43 +00:00

73 lines
2.2 KiB
Go

package articles
import (
"github.com/gin-gonic/gin"
"github.com/gosimple/slug"
"github.com/gothinkster/golang-gin-realworld-example-app/common"
"github.com/gothinkster/golang-gin-realworld-example-app/users"
)
type ArticleModelValidator struct {
Article struct {
Title string `form:"title" json:"title" binding:"required,min=4"`
Description string `form:"description" json:"description" binding:"required,max=2048"`
Body string `form:"body" json:"body" binding:"required,max=2048"`
Tags []string `form:"tagList" json:"tagList"`
} `json:"article"`
articleModel ArticleModel `json:"-"`
}
func NewArticleModelValidator() ArticleModelValidator {
return ArticleModelValidator{}
}
func NewArticleModelValidatorFillWith(articleModel ArticleModel) ArticleModelValidator {
articleModelValidator := NewArticleModelValidator()
articleModelValidator.Article.Title = articleModel.Title
articleModelValidator.Article.Description = articleModel.Description
articleModelValidator.Article.Body = articleModel.Body
for _, tagModel := range articleModel.Tags {
articleModelValidator.Article.Tags = append(articleModelValidator.Article.Tags, tagModel.Tag)
}
return articleModelValidator
}
func (s *ArticleModelValidator) Bind(c *gin.Context) error {
myUserModel := c.MustGet("my_user_model").(users.UserModel)
err := common.Bind(c, s)
if err != nil {
return err
}
s.articleModel.Slug = slug.Make(s.Article.Title)
s.articleModel.Title = s.Article.Title
s.articleModel.Description = s.Article.Description
s.articleModel.Body = s.Article.Body
s.articleModel.Author = GetArticleUserModel(myUserModel)
s.articleModel.setTags(s.Article.Tags)
return nil
}
type CommentModelValidator struct {
Comment struct {
Body string `form:"body" json:"body" binding:"required,max=2048"`
} `json:"comment"`
commentModel CommentModel `json:"-"`
}
func NewCommentModelValidator() CommentModelValidator {
return CommentModelValidator{}
}
func (s *CommentModelValidator) Bind(c *gin.Context) error {
myUserModel := c.MustGet("my_user_model").(users.UserModel)
err := common.Bind(c, s)
if err != nil {
return err
}
s.commentModel.Body = s.Comment.Body
s.commentModel.Author = GetArticleUserModel(myUserModel)
return nil
}