#Middleware and context

4 messages · Page 1 of 1 (latest)

spark fiber
#

I have developed a middleware that retrieves the current user based on a cookie. Initially, I use the session ID stored in the cookie to fetch the user's details. Up to this point, everything works as expected. In the next phase of the middleware, I modify the request's context (r.Context) by adding the fetched user's data. However, when I attempt to access this user data in the models package on the server, it appears that the data transfer wasn't successful. Although my implementation seems correct, I'm puzzled as to why the user data is not present in the models package as expected.

package controllers 
type UserCtxKey string

const (
    userkey UserCtxKey = "user"
)

func SetUserContext(ctx context.Context, user *models.User) context.Context {
    return context.WithValue(ctx, userkey, user)
}
package controllers 
func (m *Middleware) GetCurrentUser(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        ctx := r.Context()
        c, err := ReadCookie(r, session)
        if err != nil {
            log.Println("Cookie error :", err)
            http.Redirect(w, r, "/login", http.StatusMovedPermanently)
            return
        }
        u, err := m.Sm.FindUserByCookie(ctx, c.Value)
        if err != nil {
            http.Error(w, "User not found", http.StatusNotFound)
            http.Redirect(w, r, "/login", http.StatusMovedPermanently)
            return
        }
        ctx = SetUserContext(ctx, u)
        r = r.WithContext(ctx)
        next.ServeHTTP(w, r)
    })
}```

```go
package models
func (lm *LanguageManager) CreateLanguage(ctx context.Context) {
    log.Println("context value of user :", ctx.Value("user"))
}
pulsar topaz
#

Hi,
You should know that (UserCtxKey)("user") != (string)("user")

#

when you getting value with ctx.Value("user"), you are using the type of string by default. But you set the value with type of UserCtxKey. So it will be the issue