英文:
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 $
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论