当前位置:网站首页>【Go实战基础】gin 如何验证请求参数
【Go实战基础】gin 如何验证请求参数
2022-07-02 06:33:00 【菜鸟实战】
目录
一、简介
实战场景: 如何使用 gin 验证请求参数
二、知识点
gin 路由
结构体
结构体参数绑定
参数验证
http 状态码
三、菜鸟实战
马上安排!
1、创建 go文件
/*
* @Author: 菜鸟实战
* @Description: gin 如何验证请求参数
*/
// 知识点:
// # gin 路由
// # 结构体
// # 结构体参数绑定
// # 参数验证
// # http 状态码
package main
// 导入包
import (
"fmt"
"github.com/gin-gonic/gin"
"net/http"
"runtime"
)
// 定义结构体
type Person struct {
Name string `form:"name" binding:"required"`
Age int `form:"age" binding:"required,gt=10"`
}
// 主函数
func main() {
// 使用内置函数打印
println("Hello", "菜鸟实战")
println("实战场景: ", "gin 如何验证请求参数")
// 初始化
r := gin.Default()
// GET 方法, 添加路由参数和回调
r.GET("/bind", testBind)
r.POST("/bind", testBind)
// 使用包函数打印
fmt.Printf("版本: %s \n", runtime.Version())
// 启动框架程序, 默认 8080 端口
r.Run()
}
// 自动根据结构体定义解析数据
func testBind(c *gin.Context) {
var person Person
// 这里是根据请求 header 的 content-type 来做 binding 操作
if err := c.ShouldBind(&person); err != nil {
c.String(http.StatusInternalServerError, "person bind error %v \n", err)
} else {
c.String(http.StatusOK, "%v \n", person)
}
}
// curl 验证方式
// bind get
// curl -X GET "http://127.0.0.1:8080/bind?a=1"
// curl -X GET "http://127.0.0.1:8080/bind?name=kitty&age=5"
// curl -X GET "http://127.0.0.1:8080/bind?name=kitty&age=21"
2、运行结果
Hello 菜鸟实战
实战场景: gin 如何验证请求参数
[GIN-debug] Listening and serving HTTP on :8080
(1)GET 方法, 添加验证范围外的路由参数和回调

(2)GET 方法, 再次添加验证范围外的路由参数和回调

(3)GET 方法, 添加验证范围内的路由参数和回调

菜鸟实战,持续学习!
边栏推荐
猜你喜欢

Openfeign facile à utiliser

汉诺塔问题的求解与分析

Kubesphere virtualization KSV installation experience

Redis安装部署(Windows/Linux)

Multi version concurrency control mvcc of MySQL

C language custom types - structure, bit segment (anonymous structure, self reference of structure, memory alignment of structure)

Flex layout

History of Web Technology

Web security -- core defense mechanism

Solution and analysis of Hanoi Tower problem
随机推荐
Gateway is easy to use
First week of JS study
群辉 NAS 配置 iSCSI 存储
Introduction to the basic concept of queue and typical application examples
OpenShift 部署应用
Function ‘ngram‘ is not defined
Pclpy projection filter -- projection of point cloud to cylinder
HackTheBox-Gunship
Openshift container platform community okd 4.10.0 deployment
OpenShift 容器平台社区版 OKD 4.10.0部署
win10使用docker拉取redis镜像报错read-only file system: unknown
Multi version concurrency control mvcc of MySQL
Gocv image reading and display
kubernetes部署loki日志系统
Oracle related statistics
查看was发布的应用程序的端口
Minecraft plug-in service opening
2022/2/13 summary
Minecraft群组服开服
Sentinel easy to use