LoginSignup
26
16

More than 5 years have passed since last update.

Ginの Middleware と HandlerFunc でデータの受け渡し

Last updated at Posted at 2016-03-04

gin.*Context.Setgin.*Context.Getで、同一リクエストに限ったデータの受け渡しが可能。

ユーザー認証で使用する例

Middleware でユーザーを認証して、HandlerFunc で認証済みのユーザーを取得。

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

// Midleware
func AuthRequired() gin.HandlerFunc {
    return func(c *gin.Context) {
        // Some authorization in Authorization
        user := Authorization()
        c.Set("AuthorizedUser", user)
    }
}

// HandlerFunc
func GetProfile(c *gin.Context) {
    user := c.Get("AuthorizedUser")
}


func main() {
    r := gin.Default()
    r.Use(AuthRequired())
    r.GET("/profile", GetProfile)
    r.run()
}
26
16
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
26
16