Gin框架速学:内置验证器的初步使用

本文介绍了一个使用Go语言创建新闻API的过程,包括模型定义、DAO层业务代码实现及路由设置。通过gin框架处理HTTP请求,利用内置验证器进行数据校验。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

准备

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
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值