Gin学习笔记

基于业务需求,需借助Gin框架封装通用功能,在此记录Gin使用笔记。(在线许愿:有机会学习Gin源码❤️‍🩹)

一、基本操作及测试

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

【代码】简单的启动示例

func main() {
	api := gin.Default()
	api.GET("/test", GetTestEndpoint)
	api.Run(":8080")
}

func GetTestEndpoint(c *gin.Context) {
	resp := map[string]string{"hello": "world"}
	c.JSON(200, resp)
}

【终端】运行试试看

[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    /test                     --> main.GetTestEndpoint (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 :8080

程序等待,这是因为没有触发/test,下面我们模拟触发
搬出我们Apifox

【测试】

本地环境:127.0.0.1:8080
新建GET接口,参数:/test
触发:发送

【终端】终端
【前端】
前端


【代码】添加中间件示例

package main

import (
	"fmt"
	"github.com/gin-gonic/gin"
)

func main() {
	r := gin.Default()
	r.Use(TestMiddleware())

	r.GET("/test", TestPrint(), func(c *gin.Context) {
		c.JSON(200, map[string]interface{}{
			"code": 1,
			"msg":  "【Hello world!】",
		})
	})
	r.Run(":8080")
}

func TestMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		path := c.FullPath()
		method := c.Request.Method
		fmt.Println("请求路径:", path, "请求方法:", method)
	}
}

func TestPrint() gin.HandlerFunc {
	return func(c *gin.Context) {
		c.Writer.WriteString("Hello!")
		c.Next()
		fmt.Println("请求状态码:", c.Writer.Status())
	}
}

【终端】运行加载
加载

【测试】

本地环境:127.0.0.1:8080
新建GET接口,参数:/test
触发:发送

【终端】
终端2

【前端】
前端2

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值