Gin框架笔记
环境搭建安装
-
设置代理镜像
由于访问GitHub速度缓慢且可能有权限问题,我们需要设置一个代理
go env -w GOPOXY=https://goproxy.io,direct
-
下载gin框架
go get -u github.com/gin-gonic/gin
-
第一个代码
func main() { r := gin.Default()//引擎初始化 r.GET("/hello", func(c *gin.Context) {//context为文本工具 fmt.Println(c.FullPath()) //打印端口号 c.Writer.Write([]byte("Hello gin\n")) //面对get请求写入一个切片数据 }) r.Run() // 监听并在 0.0.0.0:8080 上启动服务 }
若要指定端口
r.Run(":8090") //在 :8090端口上运行
请求处理
引擎创建
下列两个语句都是用来创建引擎的。
engine1 = gin.Default()
engine2 = gin.New()
两个语句的区别是 gin.Default()
也会使用 gin.New()
创建 engine
实例,不过会默认调用Logger
和 Recovery
中间件更方便于操作。
Logger
是负责进行打印并输出日志的中间件,方便开发者进行程序调试;REcovery
会恢复程序执行,并返回服务器500内部错误。通常情况我们都默认使用 gin.Default()
创建 Engine 实例。
处理语句
Handle通用请求
engine.Handle(`方法`"GET",`path`"/hello",func(c *gin.Context){
})
GET请求
基本框架
engine.GET("`路径`path",func(context *gin.Context`上下文结构体`){
"相关操作"
})
相关操作
//http://localhost:8080/hello?name=Goland
//调用路径
fmt.Println(context.FullPath())
//解析路径值的两种方法
name := context.DefaultQuery(`key值:`"name",`默认值:`"hello")
name := context.Query(`key值:`"name")
POST请求
基本框架
engine.POST("`路径`path",func(context *gin.Context){
})
相关操作
//http://localhost:8080/login
//内容在表单中
fmt.Println(context.FullPath())
//获取对应值
username := context.PostForm("username")
//获取对应值,并返回是否获取成功
password,exist:= context.GETPostForm("password")
if exist{
context.Writer.Write([]byte("成功获取密码"))
}
DELETE请求
基本框架
由于id
是变化的,所以用:
去获取id的值。
engine.DELETE("/user/:id",func(context *gin.Context){
})
相关操作
//获取ID为例位置的变量
userID := context.Param(`key值`"id")
综合实例
//http://localhost:8080/hello?name=Goland
engine := gin.Default()
//GET请求
engine.GET("path",func(context *gin.Context){
fmt.Println(context.FullPath())
//第一种,如果查询不到name的值就给name一个默认值
name := context.DefaultQuery(`key:`"name",`default:`"hello")
//第二种,直接查询没有默认值
name := context.Query(`key:`"name")
})
//POST请求
engine.POST("path",fun(context *gin.Context){
fmt.Println(context.FullPath())
//第一种只获取对应值
username := context.PostForm("对应key值(例如username)")
//第二种会返回第二参数,表示是否获取到了对应值
username,exist := context.GetPostForm(`key:`"username")
//判断是否获取到了,然后做处理
if exist{
"对应处理"
fmt.Println(username)
}
})
//DELETE请求
engine.DELETE("/user/:id",func(context *gin.Context){
//获取id位置变量
uesID := context.Param("id")
})
请求参数绑定和多数据处理格式
前导
我们通过请求处理的基本学习,可以了解到如何获得表单数据,但是我们的样例中只有username
和 password
两个数据需要获取,但实际项目中我们需要获取多个数据,这样一次获取一个数据开发效率就相对较慢,且封装性差。
Gin框架就提供了表单实体绑定的功能,可以将表单数据与我们自己定义的结构进行绑定。
表单实体绑定
Gin框架提供了数据结构体和表单提交数据绑定的功能,提高表达数据获取的效率。如下所示:
以一个学生学习获取为实例。表单提交的时候包含两个数据:Name和Classes
type Student struct{
Name string `form:"name" binding:"required"`
Classes string `form:"classes" binding:"required"`
}
创建一个Student
结构用于接受学生数据,通过 tag
标签的方式设置结构体中每个数据对应字段所 form
(绑定)的属性名,binding
则是设置属性是否必须,默认是必须。
这里要注意一个要点,结构体中的变量定义必须是大写,否则无法成功获取到对应绑定的值。
ShouldBindQuery
使用 ShouldBindQuery
可以实现 GET
方式的数据请求的绑定,实现如下:
func main(){
engine := gin.Default()
//htpp://localhos:8080/hello?name=davie&classes=软件工程
engine.GET("/hello",func(context *gin.Context){
fmt.Println(context.FullPath())
//定义结构体变量
var stu Student
//定义错误返回信息,成功绑定stu则无返回值
err := context.ShouldBindQuery(&stu)
if err != nil{
//绑定失败输出错误日志
log.Fatal(err.Error())
return
}
fmt.Println(stu.Name)
fmt.Println(stu.Classes)
context.Writer.Write([]byte("hello," + stu.Name))
})
}
type Student struct{
Name string `form:"name"`
Classes string `form:"classes"`
}
这里触及到 log
日志的包语句,log.Fatal(输出内容)
用来输出日志,方便开发者查询错误。
ShouldBind
使用ShouldBind可以实现Post方式的提交数据的绑定工作,具体如下:
func main() {
engine := gin.Default()
engine.POST("/register", func(context *gin.Context) {
fmt.Println(context.FullPath())
//定义结构体变量
var reg Register
//绑定并判断是否绑定成功
if err := context.ShouldBind(®); err != nil {
log.Fatal(err.Error())
return
}
fmt.Println(reg.UserName)
fmt.Println(reg.Phone)
context.Writer.Write([]byte(reg.UserName + " Register "))
})
engine.Run()
}
type Register struct {
UserName string form:"name"
Phone string form:"phone"
Password string form:"pwd"
}
ShouldBindJson
当客户端使用 Json
格式进行数据提交时,可以采用 ShouldBindJson
对数据进行绑定
func main() {
engine := gin.Default()
engine.POST("/addstudent", func(context *gin.Context) {
fmt.Println(context.FullPath())
//1
var person Person
//2
if err := context.BindJSON(&person); err != nil {
log.Fatal(err.Error())
return
}
fmt.Println("姓名:" + person.Name)
fmt.Println("年龄:", person.Age)
context.Writer.Write([]byte(" 添加记录:" + person.Name))
})
engine.Run()
}
type Person struct {
Name string form:"name"
Sex string form:"sex"
Age int form:"age"
}