package main import ( "context" "net/http" ) type CtxUser string func (s Server) AuthorizedOnly(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { sessionHeader := r.Header.Get("SessionID") session, err := s.db.GetSessionByToken(sessionHeader) if err != nil { w.WriteHeader(http.StatusUnauthorized) return } user, err := s.db.GetUserByID(session.UserID) if err != nil { w.WriteHeader(http.StatusUnauthorized) return } ctx := r.Context() ctx = context.WithValue(ctx, CtxUser("user"), user) next.ServeHTTP(w, r.WithContext(ctx)) }) }