当前位置: 首页 > news >正文

gin路由篇

1. 基本路由

gin 框架中采用的路由库是基于httprouter做的

import ("net/http""github.com/gin-gonic/gin"
)func main() {// 1.创建路由r := gin.Default()// 2.绑定路由规则,执行的函数// gin.Context,封装了request和responser.GET("/", func(c *gin.Context) {c.String(http.StatusOK, "hello World!")})// 3.监听端口,默认在8080// Run("里面不指定端口号默认为8080") r.Run(":8000")
}

2. Restful风格的API

gin支持Restful风格的API

  • 获取文章 /blog/getXxx Get blog/Xxx
  • 添加 /blog/addXxx POST blog/Xxx
  • 修改 /blog/updateXxx PUT blog/Xxx
  • 删除 /blog/delXxxx DELETE blog/Xxx

3. API参数

可以通过Context的Param方法来获取API参数

package mainimport ("net/http""strings""github.com/gin-gonic/gin"
)func main() {r := gin.Default()r.GET("/user/:name/*action", func(c *gin.Context) {name := c.Param("name")action := c.Param("action")//截取/action = strings.Trim(action, "/")c.String(http.StatusOK, name+" is "+action)})//默认为监听8080端口r.Run(":8000")
}

4. URL参数

  • URL参数可以通过DefaultQuery()或Query()方法获取
  • DefaultQuery()若参数不村则,返回默认值,Query()若不存在,返回空串
  • API?name=zs
package mainimport ("fmt""net/http""github.com/gin-gonic/gin"
)func main() {r := gin.Default()r.GET("/user", func(c *gin.Context) {//指定默认值//http://localhost:8080/user 才会打印出来默认的值name := c.DefaultQuery("name", "枯藤")c.String(http.StatusOK, fmt.Sprintf("hello %s", name))})r.Run()
}

5. 表单参数

  • 表单传输为post请求,http常见的传输格式为四种:
    • application/json
    • application/x-www-form-urlencoded
    • application/xml
    • multipart/form-data
  • 表单参数可以通过PostForm()方法获取,该方法默认解析的是x-www-form-urlencoded或from-data格式的参数
    <form action="http://localhost:8080/form" method="post" action="application/x-www-form-urlencoded">用户名:<input type="text" name="username" placeholder="请输入你的用户名">  <br>密&nbsp;&nbsp;&nbsp;码:<input type="password" name="userpassword" placeholder="请输入你的密码">  <br><input type="submit" value="提交"></form>
package main//
import ("fmt""net/http""github.com/gin-gonic/gin"
)func main() {r := gin.Default()r.POST("/form", func(c *gin.Context) {types := c.DefaultPostForm("type", "post")username := c.PostForm("username")password := c.PostForm("userpassword")// c.String(http.StatusOK, fmt.Sprintf("username:%s,password:%s,type:%s", username, password, types))c.String(http.StatusOK, fmt.Sprintf("username:%s,password:%s,type:%s", username, password, types))})r.Run()
}

6. 上传单个文件

  • multipart/form-data格式用于文件上传

  • gin文件上传与原生的net/http方法类似,不同在于gin把原生的request封装到c.Request中

<form action="http://localhost:8080/upload" method="post" enctype="multipart/form-data">上传文件:<input type="file" name="file" ><input type="submit" value="提交"></form>
package mainimport ("github.com/gin-gonic/gin"
)func main() {r := gin.Default()//限制上传最大尺寸r.MaxMultipartMemory = 8 << 20r.POST("/upload", func(c *gin.Context) {file, err := c.FormFile("file")if err != nil {c.String(500, "上传图片出错")}// c.JSON(200, gin.H{"message": file.Header.Context})c.SaveUploadedFile(file, file.Filename)c.String(http.StatusOK, file.Filename)})r.Run()
}

7. 上传多个文件

<form action="http://localhost:8000/upload" method="post" enctype="multipart/form-data">上传文件:<input type="file" name="files" multiple><input type="submit" value="提交"></form>
package mainimport ("github.com/gin-gonic/gin""net/http""fmt"
)// gin的helloWorldfunc main() {// 1.创建路由// 默认使用了2个中间件Logger(), Recovery()r := gin.Default()// 限制表单上传大小 8MB,默认为32MBr.MaxMultipartMemory = 8 << 20r.POST("/upload", func(c *gin.Context) {form, err := c.MultipartForm()if err != nil {c.String(http.StatusBadRequest, fmt.Sprintf("get err %s", err.Error()))}// 获取所有图片files := form.File["files"]// 遍历所有图片for _, file := range files {// 逐个存if err := c.SaveUploadedFile(file, file.Filename); err != nil {c.String(http.StatusBadRequest, fmt.Sprintf("upload err %s", err.Error()))return}}c.String(200, fmt.Sprintf("upload ok %d files", len(files)))})//默认端口号是8080r.Run(":8000")
}

8. routes group

  • routes group是为了管理一些相同的URL
package mainimport ("github.com/gin-gonic/gin""fmt"
)// gin的helloWorldfunc main() {// 1.创建路由// 默认使用了2个中间件Logger(), Recovery()r := gin.Default()// 路由组1 ,处理GET请求v1 := r.Group("/v1")// {} 是书写规范{v1.GET("/login", login)v1.GET("submit", submit)}v2 := r.Group("/v2"){v2.POST("/login", login)v2.POST("/submit", submit)}r.Run(":8000")
}func login(c *gin.Context) {name := c.DefaultQuery("name", "jack")c.String(200, fmt.Sprintf("hello %s\n", name))
}func submit(c *gin.Context) {name := c.DefaultQuery("name", "lily")c.String(200, fmt.Sprintf("hello %s\n", name))
}

9. 路由原理

  • httproter会将所有路由规则构造一颗前缀树

  • 例如有 root and as at cn com

参考文章:

https://www.fansimao.com/928594.html

https://www.fansimao.com/928610.html

https://www.fansimao.com/928613.html

http://www.lryc.cn/news/287176.html

相关文章:

  • C++逆向分析--继承的本质
  • ​LeetCode解法汇总2865. 美丽塔 I
  • pinia 的使用方法
  • sky_take_out
  • LC 2865. 美丽塔 I
  • 代理设计模式JDK动态代理CGLIB动态代理原理
  • [陇剑杯 2021]webshell
  • 美易官方:小米汽车交付时间传闻被官方辟谣
  • MySQL 简介
  • 动态规划最后一天(回文串)
  • c语言之scanf函数
  • ORM-02-JPA Java Persistence API 注解入门介绍
  • 【MQ01】什么是消息队列?用哪个消息队列?
  • 2023年度AI盘点 AIGC|AGI|ChatGPT|人工智能大模型
  • 【Flink-CDC】Flink CDC 介绍和原理概述
  • 长城资产信息技术岗24届校招面试面经
  • 【计算机网络】TCP握手与挥手:三步奏和四步曲
  • 设计模式学习总结
  • 「HDLBits题解」Cellular automata
  • 什么是API ?
  • Pytest中conftest.py的用法
  • java.lang.IllegalArgumentException: When allowCredentials is true
  • vue折叠展开transition动画使用keyframes实现
  • 书生·浦语大模型实战营-学习笔记5
  • 10. Profile
  • YOLO 自己训练一个模型
  • 3.Eureka注册中心
  • 基于springboot+vue的墙绘产品展示交易平台系统(前后端分离)
  • 网络原理-初识(1)
  • 【GitHub项目推荐--人脸识别】【转载】