-
|
For example, in Java, I can save user information in ThreadLocal and automatically inject information such as CreateId and CreateName into ORM hooks. How to implement similar functionality in go&echo and inject user information into ORM hooks. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 4 replies
-
|
Go doesn't have ThreadLocal like Java, but 1. Store user info in middleware: func UserMiddleware(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
user := getUserFromToken(c) // your auth logic
c.Set("user", user)
return next(c)
}
}2. Pass context to your DB/ORM layer: func CreateOrder(c echo.Context, order *Order) error {
ctx := c.Request().Context()
// Pass ctx to your ORM
return db.WithContext(ctx).Create(order).Error
}3. In your ORM hooks, extract user from context: For GORM, you can use callbacks: func (o *Order) BeforeCreate(tx *gorm.DB) error {
ctx := tx.Statement.Context
if user, ok := ctx.Value("user").(*User); ok {
o.CreateId = user.ID
o.CreateName = user.Name
}
return nil
}Important: You need to bridge Echo's context with Go's func InjectUserToContext(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
user := c.Get("user")
ctx := context.WithValue(c.Request().Context(), "user", user)
c.SetRequest(c.Request().WithContext(ctx))
return next(c)
}
}This way the user info flows through Unlike Java's ThreadLocal which is tied to a thread, Go's context is explicitly passed - which is actually safer since goroutines can be reused and you won't accidentally leak data between requests. |
Beta Was this translation helpful? Give feedback.
I found the
github.com/timandy/routineand can doMiddleware
Anywhere