安装
go get -u github.com/gin-gonic/gin
Gin 路由
入门
gin.Default() 中 Default()中的代码
engine := New()
//默认用了两个中间件,日志和恢复
engine.Use(Logger(), Recovery()) 中间件
-
基本路由
Gin框架中采用的路由库是基于 httprouter做的
-
Restful风格的API
Gin支持Restful风格的API
Representational State Transfer的缩写,表现层状态转化,是互联网应用程序的API设计理念:URL定位资源,用HTTP描述操作
-
API参数
通过 Context的Param方法来获取API
Localhost:8080/xxx/zhangsan 后面的这个zhangsan就是API参数
-
表单参数
表单传输为Post请求,http常见的传输格式为四种:
application/json
application/x-www.form.urlencoded
application/xml
multipart/form-data
表单参数可以通过 PostForm()方法获取,该方法默认解析的是x-www.form.urlencoded或form-data格式的参数。
//后端代码
func main() {
// gin 的 hello world
/*
1.创建路由
gin.Default()----》engine := New()
engine.Use(Logger(), Recovery()) 中间件
*/
r := gin.Default()
/*
* 代表 接收任意的;
匹配的规则
*/
r.POST("/form", func(c *gin.Context) {
/*
表单参数也可以设置默认值,form表单中没有 type
*/
type1 := c.DefaultPostForm("type", "alert")
userName := c.PostForm("username")
passworld := c.PostForm("password")
//gin中写兴趣的多选框
hobbies := c.PostFormArray("hobby")
c.String(http.StatusOK,
fmt.Sprintf("type is %s, userName = %s, password = %s, hobby is %v",
type1, userName, passworld, hobbies))
//name := c.DefaultQuery("name", "jack")
//c.String(http.StatusOK, fmt.Sprintf("Hello %s ", name))
/*
http://localhost:8000/welcome?name=tommy
*/
})
r.Run("localhost:8000")
}
func getting(ctx *gin.Context) {
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>登陆</title>
</head>
<body>
<form action="http://127.0.0.1:8000/form" method="post" enctype="application/x-www-form-urlencoded">
用户名:<input type="text" name="username">
<br>
密  码:<input type="password" name="password">
兴  趣:
<input type="checkbox" value="run" name="hobby"> 跑步
<input type="checkbox" value="run" name="hobby"> 足球
<input type="checkbox" value="run" name="hobby"> 篮球
<input type="checkbox" value="run" name="hobby"> 游泳
<br>
<input type="submit" value="登陆">
</form>
</body>
</html>
-
上传单个文件
multipart/form-data格式用于文件上传
Gin文件上传与原生的net/http方法类似,不同于原生的request封装到c.Request中
-
上传多个文件
<input type="file" name="files" multiple>
package main import ( "fmt" "github.com/gin-gonic/gin" "net/http" ) func main() { engin := gin.Default