Please enable Javascript to view the contents

go-gin框架使用

 ·  ☕ 2 分钟 · 👀... 阅读

前提准备

1.1配置go代理并开启go mod模式:

1
2
go env -w GO111MODULE="on"
go env -w GOPROXY="https://goproxy.cn,direct"

1.2使用go mod初始化项目并下载依赖包

1
2
go mod init mypoject
go mod tidy

1.3下载gin框架

1
go get -u github.com/gin-gonic/gin

快速入门

运行下列代码并访问http://localhost:8080/helloworld您将看到效果。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
package main

import "github.com/gin-gonic/gin"

func main() {
    //初始化路由
    r := gin.Default()
    //当访问http://localhost:8080/helloworld的时候就会执行匿名函数
    r.GET("/helloworld", func(c *gin.Context) {
        // c.JSON:返回JSON格式的数据
        c.JSON(200, gin.H{
            "message": "helloworld!",
        })
    })
    r.Run() // listen and serve on 0.0.0.0:8080
}

Run()方法默认是8080端口,如果想要改变端口,可以:Run(":9000"),这样就变成了9000端口。

代码示例

如下列代码,虽然访问的路由是一样的,当路由请求的方式不一样,这样就不会造成问题。

使用浏览器获取其他请求麻烦?来试试ApiPost:https://www.apipost.cn/download.html

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
func main() {
	r := gin.Default()
	r.GET("/test", func(c *gin.Context) {
		c.JSON(200, gin.H{
			"message": "GET",
		})
	})

	r.POST("/test", func(c *gin.Context) {
		c.JSON(200, gin.H{
			"message": "POST",
		})
	})

	r.PUT("/test", func(c *gin.Context) {
		c.JSON(200, gin.H{
			"message": "PUT",
		})
	})

	r.DELETE("/test", func(c *gin.Context) {
		c.JSON(200, gin.H{
			"message": "DELETE",
		})
	})
}

会不会发现上面我们的路由组都是独立的,看着没有秩序?来试试路由组

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
func main() {
	r := gin.Default()
    v1 = r.Group("/v1")
    {
       	v1.GET("/test", func(c *gin.Context) {
		c.JSON(200, gin.H{
			"message": "GET",
			})
		})

        v1.POST("/test", func(c *gin.Context) {
            c.JSON(200, gin.H{
                "message": "POST",
            })
        })

        v1.PUT("/test", func(c *gin.Context) {
            c.JSON(200, gin.H{
                "message": "PUT",
            })
        })

        v1.DELETE("/test", func(c *gin.Context) {
            c.JSON(200, gin.H{
                "message": "DELETE",
            })
        }) 
    }
}

现在的话,我们这四种路由请求都数据v1的这个路由组下面,这时候如果想要访问路由的话就需要在子路由前加上路由组的URI,如v1.Get请求:http://127.0.0.1:8080/v1/test

分享

幽梦
作者
幽梦
傻猪男孩

目录