在Gin中,如果不进行编组,如何将结构体从中间件传递给处理程序?

huangapple go评论67阅读模式
英文:

How to pass a struct from middleware to handler in Gin without marshalling?

问题

我有一个从源获取数据(结构体)的 Gin 中间件:

type Data struct {
  Key1 string
  Key2 int
  Key3 bool
}

func GetData() Data {
  // 返回 Data 的实例
}

func Middleware(ctx *gin.Context) {
  data := GetData()

  // 我需要将数据(结构体)添加到 ctx 中以传递给处理程序
}

使用 ctx.Set() 需要进行编组,而且稍后解组很困难。

有没有一种方法可以直接将数据传递给处理程序?如果没有,是否有一种安全的编组/解组方法?

英文:

I have a Gin middleware that gets data (struct) from a source:

type Data struct {
  Key1 string
  Key2 int
  Key3 bool
}

func GetData() Data {
  // returns instant of Data
}

func Middleware(ctx *gin.Context) {
  data := GetData()

  // I need to add data (struct) to ctx to pass to handler
}

With ctx.Set() I have to marshal and it's hard to unmarshal later.

Is there a way to pass the data to the handler as is? If not, is there a way marshal/unmarshal safely?

答案1

得分: 1

我不确定我是否理解了问题,但是以下是我尝试的内容,以防有帮助(我通过上下文传递了数据,并在处理程序中获取到了它):

package main

import (
	"fmt"

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

type Data struct {
	Key1 string
	Key2 int
	Key3 bool
}

func getData() Data {
	return Data{"test", 10, true}
}

func myMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		c.Set("data", getData())
		c.Next()
	}
}

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

	r.GET("/test", func(c *gin.Context) {
		data, _ := c.Get("data")

		c.JSON(200, gin.H{
			"message": "pong",
			"data":    data,
		})
	})
	r.Run()
}

输出:

 ~/Projects/go/q69600198 $ curl 127.0.0.1:8080/test
{"data":{"Key1":"test","Key2":10,"Key3":true},"message":"pong"}

 ~/Projects/go/q69600198 $
英文:

Not exactly sure if I understood the questions, but here is what I tried, just in case it helps (I passed the Data through the context and got it in the handler):

package main

import (
	"fmt"

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

type Data struct {
	Key1 string
	Key2 int
	Key3 bool
}

func getData() Data {
	return Data{"test", 10, true}
}

func myMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		c.Set("data", getData())
		c.Next()
	}
}

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

	r.GET("/test", func(c *gin.Context) {
		data, _ := c.Get("data")

		c.JSON(200, gin.H{
			"message": "pong",
			"data":    data,
		})
	})
	r.Run()
}

output:

 ~/Projects/go/q69600198 $ curl 127.0.0.1:8080/test
{"data":{"Key1":"test","Key2":10,"Key3":true},"message":"pong"}

 ~/Projects/go/q69600198 $

huangapple
  • 本文由 发表于 2021年10月17日 07:11:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/69600198.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定