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

Time:10-18

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?

CodePudding user response:

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 $
  •  Tags:  
  • go
  • Related