go-gin框架的使用

295 阅读3分钟

「这是我参与2022首次更文挑战的第15天,活动详情查看:2022首次更文挑战

前言

Gin是一个golang的微框架,封装比较优雅,API友好,源码注释比较明确。对于golang而言,web框架的依赖要远比Python,Java之类的要小。自身的net/http足够简单,性能也非常不错借助框架开发,不仅可以省去很多常用的封装带来的时间,也有助于团队的编码风格和形成规范。

gin框架使用

在go.mod文件引入如下gin框架

module ginstudy
go 1.16
require ( 
  github.com/gin-gonic/gin v1.7.7
)

然后我们在main函数写一个方法

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

跑起来这个方法就可以看到控制台输出如下

/private/var/folders/z8/4tqvzxl52qdgbxbfjkz2q9xr0000gn/T/___go_build_ginstudy
[GIN-debug] [WARNING] Creating an Engine instance with the Logger and Recovery middleware already attached.

[GIN-debug] [WARNING] Running in "debug" mode. Switch to "release" mode in production.
 - using env:   export GIN_MODE=release
 - using code:  gin.SetMode(gin.ReleaseMode)

[GIN-debug] GET    /                         --> main.main.func1 (3 handlers)
[GIN-debug] [WARNING] You trusted all proxies, this is NOT safe. We recommend you to set a value.
Please check https://pkg.go.dev/github.com/gin-gonic/gin#readme-don-t-trust-all-proxies for details.
[GIN-debug] Listening and serving HTTP on :8000

表示已经启动了一个8000的服务端口。

然后在浏览器访问,就能看到输出的结果了,这就是最基础的用法。

gin路由

gin的路由来自httprouter库,我们可以定义好其他路由,然后启动服务,如下。

定义了额外的2个路由

r.GET("/", func(c *gin.Context) {   c.String(http.StatusOK, "hello World!")})r.GET("/getUserInfo", func(c *gin.Context) {   c.String(http.StatusOK, "这是getUserInfo接口!")})r.POST("/login", func(c *gin.Context) {   c.String(http.StatusOK, "login接口!")})

访问新的getUserInfo接口,get请求即可以得到对应的信息。

所以想要什么样的接口,我们就可以在这里定义出来,然后在后面写出对应的业务。

获取参数 c.Param

这种获取形式的参数,需要路由定义为如下图才行,/ 后面加入值。

r.GET("/getUserInfo/:id", func(c *gin.Context) {   Id := c.Param("id")   c.String(http.StatusOK, Id+" 传过来了 ")})

c.DefaultQuery

r.GET("/user", func(c *gin.Context) {   Id := c.DefaultQuery("id", "12")   c.String(http.StatusOK, Id+" url参数 ")})

这种形式获取参数就是可以直接从url获取。

c.PostForm

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))})
  • 表单传输为post请求,http常见的传输格式为四种:
    • application/json
    • application/x-www-form-urlencoded
    • application/xml
    • multipart/form-data
  • 表单参数可以通过PostForm()方法获取,该方法默认解析的是x-www-form-urlencoded或from-data格式的参数

这个参数的方式就是要定义对应的请求头才可以。

总结

本文主要讲解了gin框架最基础的使用,包括怎么获取参数。实际开发中,我们可以根据具体的业务来设置请求接口,简单的可以使用get,直接从url获取参数。对于post请求可以使用绑定数据解析的方式来实现,下一篇在讲。