Gin框架入门之Rest操作、Query操作、提交表单、上传单个文件、上传多个文件用法

本文主要是介绍Gin框架入门之Rest操作、Query操作、提交表单、上传单个文件、上传多个文件用法,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

在这里插入图片描述

文章目录

    • @[toc]
  • 1. 基本路由操作
  • 2. Restful风格的API
    • 2.1 API参数
    • 2.2 URL参数
      • 2.5 表单数据
      • 2.6上传单个文件
      • 2.7上传多个文件
      • 2.8 Route Group

1. 基本路由操作

  • gin框架采用的路由库是基于httprouter做的
  • httprouter链接:https://github.com/julienschmidt/httprouter

gin的基本路由框架如下:

package mainimport ("net/http""github.com/gin-gonic/gin"
)func getHandler(c *gin.Context) {c.String(http.StatusOK, "这是查询操作")
}
func addHandler(c *gin.Context) {c.String(http.StatusOK, "这是ADD操作")
}
func modifyHandler(c *gin.Context) {c.String(http.StatusOK, "这是PUT操作")
}
func main() {r := gin.Default()r.GET("/xxx", getHandler)r.POST("/xxx", addHandler)r.PUT("/xxx", modifyHandler)r.Run()
}

编译运行:go run main.go

为了方便测试,这里使用Postman软件进行测试验证。
请添加图片描述

2. Restful风格的API

  • gin支持Restful风格的API
  • 即Representational State Transfer的缩写。直接翻译的意思是"表现层状态转化",是一种互联网应用程序的API设计理念:URL定位资源,用HTTP描述操作
序号操作url
1获取文章/blog/getXxxGet blog/Xxx
2添加/blog/addXxxPOST blog/Xxx
3修改/blog/updateXxxPUT blog/Xxx
4删除/blog/delXxxDELETE blog/Xxx

2.1 API参数

在REST-API中传递参数的方式有多种:

  • 通过定义的API传递参数
  • 通过Query操作传递URL参数
  • 在Header中传递参数
  • 在Body中传递参数

后面两个比较常见。这里主要是前两个:API参数URL参数

API参数说的是:在定义API时,通过占位符的方式给可能需要传递的参数预留位置。在Gin框架中可以通过Context的Param方法来获取这部分参数。

package mainimport ("fmt""net/http""strings""github.com/gin-gonic/gin"
)func main() {r := gin.Default()r.GET("/user/:name/*passwd", func(c *gin.Context) {name := c.Param("name")passwd := c.Param("passwd")//此时passwd="/xxxxx", 需要截断passwd(去除/)passwd = strings.Trim(passwd, "/")fmt.Printf("name=%s, passwd=%s\n", name, passwd)c.String(http.StatusOK, fmt.Sprintf("name=%s, passwd=%s\n", name, passwd))})r.Run(":8080")
}

编译运行:go run main.go

在浏览器中输入相应的API,结果如下:
请添加图片描述

已经从API中成功获取到了用户名和密码信息。

2.2 URL参数

URL参数一般是通过HTTP的Query方法来传递的。例如:https://cn.bing.com/search?q=aaa

其中:?q=aaa 便是Query的查询条件,也就是我们说的URL参数。不过URL参数不包括那个’?’

  • Gin框架中,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) {name, _ := c.GetQuery("name")passwd, _ := c.GetQuery("passwd")fmt.Printf("name=%s, passwd=%s\n", name, passwd)c.String(http.StatusOK, fmt.Sprintf("name=%s, passwd=%s\n", name, passwd))})r.Run(":8080")
}

编译运行:go run main.go

在浏览器查看结果如下:
请添加图片描述

2.5 表单数据

http常见的传输格式有四种:

  • application/json
  • application/x-www-form-urlencoded
  • application/xml
  • mutipart/form-data

客户端向服务端提交数据时,通常采用表单的方式进行传输。例如提交用户名、密码、评论信息大多数都是采用表单的方式提交。这里简答介绍下gin中对表单数据的处理。

在Gin框架中,使用PostForm()方法获取表单参数,该方法默认解析的是:x-www-form-urlencoded或者form-data数据。DefaultPostForm()如果没有获取到指定的参数,则会填充默认字段。

demo如下:

package mainimport ("fmt""net/http""github.com/gin-gonic/gin"
)func handler(c *gin.Context) {user := c.PostForm("user")passwd := c.PostForm("passwd")types := c.DefaultPostForm("phone", "13031000000")c.String(http.StatusOK, fmt.Sprintf("用户名:%s, 密码:%s,联系方式:%s", user, passwd, types))
}func main() {r := gin.Default()r.POST("/golang/web/gin/form-data", handler)r.Run()
}

上次用的Postman进行测试,但是我用的比较少,不太习惯;如果自己再写一个提交表单的web页面,也着实有点难为人。最近一直在使用Eolinker进行项目管理,因此使用eolinker对该接口进行测试,个人感觉eolinker特别好用,强烈推荐一波。

请添加图片描述

2.6上传单个文件

http使用mutipart/form-data格式进行文件传输。

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

package mainimport ("net/http""github.com/gin-gonic/gin"
)func upload(c *gin.Context) {file, err := c.FormFile("file")if err != nil {c.String(http.StatusNotImplemented, "上传文件失败")return}c.SaveUploadedFile(file, file.Filename)c.String(http.StatusOK, "接收文件成功:", file.Filename)
}func main() {r := gin.Default()r.MaxMultipartMemory = 8 << 20 //8Mr.POST("/golang/web/gin/upload", upload)r.Run()
}

测试效果:

请添加图片描述

2.7上传多个文件

接收多个文件,在代码处理上有些微不同,不过在Eolinker上的测试不用修改,直接导入多个文件即可。

package mainimport ("fmt""net/http""github.com/gin-gonic/gin"
)func uploadFiles(c *gin.Context) {form, err := c.MultipartForm()if err != nil {c.String(http.StatusNotImplemented, "上传文件失败")return}fmt.Printf("%+v\n", form)files := form.File["file"]//需要与eolinker上的参数名保持一致for _, file := range files {if err = c.SaveUploadedFile(file, file.Filename); err != nil {c.String(http.StatusNotImplemented, "上传文件失败")return}c.String(http.StatusOK, "接收文件成功:", file.Filename)}}func main() {r := gin.Default()r.MaxMultipartMemory = 8 << 20 //8Mr.POST("/golang/web/gin/upload", uploadFiles)r.Run()
}

测试效果如下:
请添加图片描述

2.8 Route Group

route group主要是为了管理一些具有相同前缀的URL.

将上面提到的几种常见用法注册到一个group中,然后进行测试。

package mainimport ("fmt""net/http""strings""github.com/gin-gonic/gin"
)func helloGin(c *gin.Context) {fmt.Println("hello Gin")c.String(http.StatusOK, "欢迎来到三体世界")
}//使用Query进行参数传递
func urlParam(c *gin.Context) {name, _ := c.GetQuery("name")passwd, _ := c.GetQuery("passwd")fmt.Printf("name=%s, passwd=%s\n", name, passwd)c.String(http.StatusOK, fmt.Sprintf("name=%s, passwd=%s\n", name, passwd))
}//使用rest方式进行参数传递
func apiParam(c *gin.Context) {name := c.Param("name")passwd := c.Param("passwd")//此时passwd="/xxxxx", 需要截断passwd(去除/)passwd = strings.Trim(passwd, "/")fmt.Printf("name=%s, passwd=%s\n", name, passwd)c.String(http.StatusOK, fmt.Sprintf("name=%s, passwd=%s\n", name, passwd))}//提交表单
func postForm(c *gin.Context) {user := c.PostForm("user")passwd := c.PostForm("passwd")types := c.DefaultPostForm("phone", "13031000000")c.String(http.StatusOK, fmt.Sprintf("用户名:%s, 密码:%s,联系方式:%s", user, passwd, types))
}func uploadFile(c *gin.Context) {file, err := c.FormFile("file")if err != nil {c.String(http.StatusNotImplemented, "上传文件失败")return}c.SaveUploadedFile(file, file.Filename)c.String(http.StatusOK, "接收文件成功:", file.Filename)
}func uploadFiles(c *gin.Context) {form, err := c.MultipartForm()if err != nil {c.String(http.StatusNotImplemented, "上传文件失败")return}fmt.Printf("%+v\n", form)files := form.File["file"]for _, file := range files {if err = c.SaveUploadedFile(file, file.Filename); err != nil {c.String(http.StatusNotImplemented, "上传文件失败")return}c.String(http.StatusOK, "接收文件成功:", file.Filename)}}
func GinMain(r *gin.RouterGroup) {ginGroup := r.Group("/gin") //gin框架前缀{ginGroup.GET("/", helloGin)ginGroup.GET("/url-param", urlParam)ginGroup.GET("/api-param/:name/:passwd", apiParam)ginGroup.POST("/form-data", postForm)ginGroup.POST("/upload/file", uploadFile)ginGroup.POST("/upload/files", uploadFiles)}
}func main() {r := gin.Default()web := r.Group("/golang/web") //公共前缀GinMain(web)//最后注册的api是将其拼接起来r.Run(":8080")
}

测试效果如下
请添加图片描述

这篇关于Gin框架入门之Rest操作、Query操作、提交表单、上传单个文件、上传多个文件用法的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/270127

相关文章

Spring Security 从入门到进阶系列教程

Spring Security 入门系列 《保护 Web 应用的安全》 《Spring-Security-入门(一):登录与退出》 《Spring-Security-入门(二):基于数据库验证》 《Spring-Security-入门(三):密码加密》 《Spring-Security-入门(四):自定义-Filter》 《Spring-Security-入门(五):在 Sprin

作业提交过程之HDFSMapReduce

作业提交全过程详解 (1)作业提交 第1步:Client调用job.waitForCompletion方法,向整个集群提交MapReduce作业。 第2步:Client向RM申请一个作业id。 第3步:RM给Client返回该job资源的提交路径和作业id。 第4步:Client提交jar包、切片信息和配置文件到指定的资源提交路径。 第5步:Client提交完资源后,向RM申请运行MrAp

数论入门整理(updating)

一、gcd lcm 基础中的基础,一般用来处理计算第一步什么的,分数化简之类。 LL gcd(LL a, LL b) { return b ? gcd(b, a % b) : a; } <pre name="code" class="cpp">LL lcm(LL a, LL b){LL c = gcd(a, b);return a / c * b;} 例题:

Java 创建图形用户界面(GUI)入门指南(Swing库 JFrame 类)概述

概述 基本概念 Java Swing 的架构 Java Swing 是一个为 Java 设计的 GUI 工具包,是 JAVA 基础类的一部分,基于 Java AWT 构建,提供了一系列轻量级、可定制的图形用户界面(GUI)组件。 与 AWT 相比,Swing 提供了许多比 AWT 更好的屏幕显示元素,更加灵活和可定制,具有更好的跨平台性能。 组件和容器 Java Swing 提供了许多

【IPV6从入门到起飞】5-1 IPV6+Home Assistant(搭建基本环境)

【IPV6从入门到起飞】5-1 IPV6+Home Assistant #搭建基本环境 1 背景2 docker下载 hass3 创建容器4 浏览器访问 hass5 手机APP远程访问hass6 更多玩法 1 背景 既然电脑可以IPV6入站,手机流量可以访问IPV6网络的服务,为什么不在电脑搭建Home Assistant(hass),来控制你的设备呢?@智能家居 @万物互联

poj 2104 and hdu 2665 划分树模板入门题

题意: 给一个数组n(1e5)个数,给一个范围(fr, to, k),求这个范围中第k大的数。 解析: 划分树入门。 bing神的模板。 坑爹的地方是把-l 看成了-1........ 一直re。 代码: poj 2104: #include <iostream>#include <cstdio>#include <cstdlib>#include <al

cross-plateform 跨平台应用程序-03-如果只选择一个框架,应该选择哪一个?

跨平台系列 cross-plateform 跨平台应用程序-01-概览 cross-plateform 跨平台应用程序-02-有哪些主流技术栈? cross-plateform 跨平台应用程序-03-如果只选择一个框架,应该选择哪一个? cross-plateform 跨平台应用程序-04-React Native 介绍 cross-plateform 跨平台应用程序-05-Flutte

MySQL-CRUD入门1

文章目录 认识配置文件client节点mysql节点mysqld节点 数据的添加(Create)添加一行数据添加多行数据两种添加数据的效率对比 数据的查询(Retrieve)全列查询指定列查询查询中带有表达式关于字面量关于as重命名 临时表引入distinct去重order by 排序关于NULL 认识配置文件 在我们的MySQL服务安装好了之后, 会有一个配置文件, 也就

Spring框架5 - 容器的扩展功能 (ApplicationContext)

private static ApplicationContext applicationContext;static {applicationContext = new ClassPathXmlApplicationContext("bean.xml");} BeanFactory的功能扩展类ApplicationContext进行深度的分析。ApplicationConext与 BeanF

bytes.split的用法和注意事项

当然,我很乐意详细介绍 bytes.Split 的用法和注意事项。这个函数是 Go 标准库中 bytes 包的一个重要组成部分,用于分割字节切片。 基本用法 bytes.Split 的函数签名如下: func Split(s, sep []byte) [][]byte s 是要分割的字节切片sep 是用作分隔符的字节切片返回值是一个二维字节切片,包含分割后的结果 基本使用示例: pa