go语言web开发系列之三:gin用go-playground/validator做参数的校验

一,演示项目的相关信息

1,项目地址:

GitHub - liuhongdi/digv03: gin用go-playground/validator做参数的校验

2,功能说明:使用校验器(validator)实现对参数的校验

3,项目结构:如图:

go语言web开发系列之三:gin用go-playground/validator做参数的校验_第1张图片

说明:刘宏缔的go森林是一个专注golang的博客,
 网站:https://blog.imgtouch.com
原文: go语言web开发系列之三:gin用go-playground/validator做参数的校验 – 架构森林

说明:作者:刘宏缔 邮箱: [email protected]

二,sql说明

CREATE TABLE `article` (
 `articleId` bigint unsigned NOT NULL AUTO_INCREMENT COMMENT 'id',
 `type` tinyint unsigned NOT NULL DEFAULT '0' COMMENT '类型',
 `subject` varchar(500) NOT NULL DEFAULT '' COMMENT '标题',
 `addTime` datetime NOT NULL DEFAULT '2020-11-19 00:00:00' COMMENT '添加时间',
 `isHot` tinyint unsigned NOT NULL DEFAULT '0' COMMENT '是否热榜,0:非热,1,热',
 `url` varchar(500) NOT NULL DEFAULT '' COMMENT '链接地址',
 `domain` varchar(100) NOT NULL DEFAULT '' COMMENT '域',
 `userId` bigint unsigned NOT NULL DEFAULT '0' COMMENT '推荐用户',
 `approvalStaffId` int unsigned NOT NULL DEFAULT '0' COMMENT '批准员工',
 `digSum` int unsigned NOT NULL DEFAULT '0' COMMENT '被顶的次数',
 `commentSum` int unsigned NOT NULL DEFAULT '0' COMMENT '被评论的次数',
 `isPublish` tinyint NOT NULL DEFAULT '0' COMMENT '0,未发布,1,已发布',
 PRIMARY KEY (`articleId`),
 KEY `isPublish` (`isPublish`)
) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='文章表'

插入6条演示数据:

INSERT INTO `article` (`articleId`, `type`, `subject`, `addTime`, `isHot`, `url`, `domain`, `userId`, `approvalStaffId`, `digSum`, `commentSum`, `isPublish`) VALUES
(1, 0, '【最近,南非发现一座大油田】石油和天然气两种重要资源是南非储量的最短板,“贫油”的帽子也一直扣在南非的头上摘不下来。可就在最近,在南非海域进行油气勘探已久的道达尔透露了其新的勘探成果:在距离南非南部海岸约175公里的奥特尼夸盆地的11B/12B地区,再次发现了重要的凝析气,可能蕴藏着大量天然气及原油。', '2020-11-19 00:00:00', 1, 'https://mp.weixin.qq.com/s/1btbmouH-2KuIHUMoucq2w', '', 1, 1, 0, 0, 1),
(2, 1, '让喵喵来开启周五的早晨吧!', '2020-11-19 00:00:00', 0, 'https://m.weibo.cn/status/4573112073720433?', 'm.weibo.cn', 0, 0, 0, 0, 1),
(3, 0, '汤姆·赫兰德、黛茜·雷德利、麦斯·米科尔森、尼克·乔纳斯主演的《混沌漫步》公开预告。影片由《明日边缘》导演道格·里曼执导,暂时定档明年1月22日上映。', '2020-11-19 00:00:00', 1, 'http://news.mtime.com/2020/11/19/1604795.html', 'news.mtime.com', 0, 0, 0, 0, 1),
(4, 1, '扫地机器人这个东西确实方便,大多数时候把房间扫的比较干净,但还有很多边边角角清扫不上,希望厂家能够在app上显示出机器人的路线图,明确告知哪些路段没有照顾到,要不然就再开发一个项目经理机器人,跟在扫地机器人屁股后面监督。//@大窑儿:可以弄个步数排行榜,让机器人们互相点赞,揣摩,攀比,内卷,无意义竞争。', '2020-11-19 00:00:00', 0, '', '', 0, 0, 0, 0, 1),
(5, 0, '【世卫组织建议医生不要使用瑞德西韦治疗新冠】世卫组织指导小组表示,证据显示,瑞德西韦对提高新冠肺炎患者的存活率没有显著影响。这项建议发表在上周五的《英国医学杂志》中。', '2020-11-19 00:00:00', 0, 'https://www.thepaper.cn/newsDetail_forward_10067542', 'thepaper.cn', 0, 0, 0, 0, 1),
(6, 0, '11月19日0—24时,31个省(自治区、直辖市)和新疆生产建设兵团报告新增确诊病例17例,均为境外输入病例(福建6例,上海4例,陕西3例,广东2例,北京1例,四川1例);无新增死亡病例;新增疑似病例1例,为本土病例(在天津)。', '2020-11-19 00:00:00', 0, 'http://m.news.cctv.com/2020/11/20/ARTIIR9o72TuDF80s6hY2IvD201120.shtml', 'm.news.cctv.com', 0, 0, 0, 0, 1);

三,go代码说明

1,pkg/validCheck/convert.go

package validCheck

import (
	"strconv"
)

type StrTo string

func (s StrTo) String() string {
	return string(s)
}

func (s StrTo) Int() (int, error) {
	v, err := strconv.Atoi(s.String())
	return v, err
}

func (s StrTo) MustInt() int {
	v, _ := s.Int()
	return v
}

func (s StrTo) UInt32() (uint32, error) {
	v, err := strconv.Atoi(s.String())
	return uint32(v), err
}

func (s StrTo) UInt64() (uint64, error) {
	v, err := strconv.Atoi(s.String())
	return uint64(v), err
}

func (s StrTo) MustUInt32() uint32 {
	curInt32, _ := strconv.Atoi(s.String())
	if (curInt32 < 0) {
		return 0;
	}
	v, _ := s.UInt32()
	return v
}

func (s StrTo) MustUInt64() uint64 {
	//fmt.Println(s)
	curInt64, _ := strconv.ParseInt(s.String(), 10, 64);
	if (curInt64 < 0) {
		return 0;
	}
	v, _ := s.UInt64()
	//fmt.Println(v)
	return v
}

2,pkg/validCheck/requestValid.go

package validCheck

import (
	"github.com/gin-gonic/gin"
	ut "github.com/go-playground/universal-translator"
	val "github.com/go-playground/validator/v10"
	"strings"
)

type ValidError struct {
	Key     string
	Message string
}

type ValidErrors []*ValidError

func (v *ValidError) Error() string {
	return v.Message
}

func (v ValidErrors) Error() string {
	return strings.Join(v.Errors(), ",")
}

func (v ValidErrors) Errors() []string {
	var errs []string
	for _, err := range v {
		errs = append(errs, err.Error())
	}

	return errs
}
//判断变量是否符合要求
func BindAndValid(c *gin.Context, v interface{}) (bool, ValidErrors) {
	var errs ValidErrors
	err := c.ShouldBind(v)
	if err != nil {
		v := c.Value("trans")
		trans, _ := v.(ut.Translator)
		verrs, ok := err.(val.ValidationErrors)
		if !ok {
			errs = append(errs, &ValidError{
				Key:     "field",
				Message: err.Error(),
			})
			return false, errs
		}
		for key, value := range verrs.Translate(trans) {
			errs = append(errs, &ValidError{
				Key:     key,
				Message: value,
			})
		}

		return false, errs
	}
	return true, nil
}

3,request/article.go

package request

type ArticleRequest struct {
	ID    uint64 `form:"id" binding:"required,gte=1"`
	//State uint8  `form:"state,default=1" binding:"oneof=0 1"`
}

type ArticleListRequest struct {
	Page int `form:"page" binding:"gte=1"`
	//State uint8  `form:"state,default=1" binding:"oneof=0 1"`
}

说明:验证的规则写在这里

4,controller/articleController.go

package controller

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/liuhongdi/digv03/global"
	"github.com/liuhongdi/digv03/pkg/page"
	"github.com/liuhongdi/digv03/pkg/validCheck"
	"github.com/liuhongdi/digv03/request"
	"github.com/liuhongdi/digv03/service"
)

type ArticleController struct{}

func NewArticleController() ArticleController {
	return ArticleController{}
}
//得到一篇文章的详情
func (a *ArticleController) GetOne(c *gin.Context) {
	result := global.NewResult(c)
	param := request.ArticleRequest{ID: validCheck.StrTo(c.Param("id")).MustUInt64()}
	valid, errs := validCheck.BindAndValid(c, ¶m)
	if !valid {
		result.Error(400,errs.Error())
		return
	}

	articleOne,err := service.GetOneArticle(param.ID);
	if err != nil {
		result.Error(404,"数据查询错误")
	} else {
		result.Success(&articleOne);
	}
	return
}

//得到多篇文章,按分页返回
func (a *ArticleController) GetList(c *gin.Context) {
	result := global.NewResult(c)
	pageInt := 0
	//is exist?
	curPage := c.Query("page")
    //if curPage not exist
    if (len(curPage) == 0) {
		pageInt = 1
	} else {
		param := request.ArticleListRequest{Page: validCheck.StrTo(c.Param("page")).MustInt()}
		valid, errs := validCheck.BindAndValid(c, ¶m)
		if !valid {
			result.Error(400,errs.Error())
			return
		}
		pageInt = param.Page
	}

	pageSize := 2;
	pageOffset := (pageInt-1) * pageSize

	articles,err := service.GetArticleList(pageOffset,pageSize)
	if err != nil {
		result.Error(404,"数据查询错误");
		fmt.Println(err.Error())
	} else {
		//sum,_ := dao.SelectcountAll()
		sum,_ := service.GetArticleSum()
		pageInfo,_ := page.GetPageInfo(pageInt,pageSize,sum)
		result.Success(gin.H{"list":&articles,"pageinfo":pageInfo});
	}
	return
}

四,测试

1,正常访问:

http://127.0.0.1:8080/article/getone/1

返回:

go语言web开发系列之三:gin用go-playground/validator做参数的校验_第2张图片

2,输入非法数据:

http://127.0.0.1:8080/article/getone/a

返回:

go语言web开发系列之三:gin用go-playground/validator做参数的校验_第3张图片

五,查看库的版本

module github.com/liuhongdi/digv03

go 1.15

require (
	github.com/gin-gonic/gin v1.6.3
	github.com/go-playground/universal-translator v0.17.0
	github.com/go-playground/validator/v10 v10.2.0
	github.com/jinzhu/gorm v1.9.16
)

你可能感兴趣的:(用go做web开发,go,golang,web,api,接口)