准备
1、创建model/NewsModel.go
文件:
package model
//新闻模型定义
type NewsModel struct {
//新闻id
Id int `json:"id"`
//新闻标题
Title string `json:"title"`
//新闻内容
Content string `json:"content"`
//作者
Author string `json:"author"`
//评分
Score int `json:"score"`
}
2、新建dao/NewsDao.go
文件:
package dao
import (
"github.com/gin-gonic/gin"
"live.go.com/model"
)
//dao层创建新闻的业务代码
func CreateNews(ctx *gin.Context) {
newsModel := model.NewsModel{}
err := ctx.BindQuery(&newsModel)
if err != nil {
ctx.String(400, "参数错误:%s", err.Error())
} else {
ctx.JSON(200, newsModel)
}
}
3、设置路由
//新闻路由分组
newsRouter := router.Group("/news")
{
//创建新闻路由
newsRouter.POST("/create",dao.CreateNews)
}
内置验证器
验证器来源一个第三方库:
https://github.com/go-playground/validator
文档:
https://godoc.org/gopkg.in/go-playground/validator.v9
type NewsModel struct {
//新闻id
Id int `json:"id"`
//新闻标题
Title string `json:"title" form:"title" binding:"required"`
//新闻内容
Content string `json:"content" binding:"min=4,max=2000"` //大于4小于200
//作者
Author string `json:"author"`
//评分
Score int `json:"score" binding:"omitempty,gt=5"` //可以不填,如果填了必须大于1
}