1. 基本路由操作
- gin框架采用的路由库是基于httprouter做的
- httprouter链接:https://github.com/julienschmidt/httprouter
gin的基本路由框架如下:
package main
import (
"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/getXxx | Get blog/Xxx |
2 | 添加/blog/addXxx | POST blog/Xxx |
3 | 修改/blog/updateXxx | PUT blog/Xxx |
4 | 删除/blog/delXxx | DELETE blog/Xxx |
2.1 API参数
在REST-API中传递参数的方式有多种:
- 通过定义的API传递参数
- 通过Query操作传递URL参数
- 在Header中传递参数
- 在Body中传递参数
后面两个比较常见。这里主要是前两个:API参数和URL参数
API参数说的是:在定义API时,通过占位符的方式给可能需要传递的参数预留位置。在Gin框架中可以通过Context的Param方法来获取这部分参数。
package main
import (
"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 main
import (
"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 main
import (
"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 main
import (
"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 //8M
r.POST("/golang/web/gin/upload", upload)
r.Run()
}
测试效果:
2.7上传多个文件
接收多个文件,在代码处理上有些微不同,不过在Eolinker上的测试不用修改,直接导入多个文件即可。
package main
import (
"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 //8M
r.POST("/golang/web/gin/upload", uploadFiles)
r.Run()
}
测试效果如下:
2.8 Route Group
route group主要是为了管理一些具有相同前缀的URL.
将上面提到的几种常见用法注册到一个group中,然后进行测试。
package main
import (
"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")
}
测试效果如下