package sessions import ( "context" "net/http" ) func StartSession(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // is there a session_token cookie? scookie, err := r.Cookie("session_token") if err != nil || scookie.Value == "" { // no session value or cookie next.ServeHTTP(w, r) return } // check for existing session cvalue := scookie.Value vsession, ok := GetSession(cvalue) if !ok { // no session next.ServeHTTP(w, r) return } // set session ctx := context.WithValue(r.Context(), SessionCtxKey("session"), vsession) next.ServeHTTP(w, r.WithContext(ctx)) }) } func GuestSession(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // if SessionKey does exist then redirect to `/u/me` as this is an auth session if v := r.Context().Value(SessionCtxKey("session")); v != nil { http.Redirect(w, r, "/u/me", http.StatusSeeOther) return } // else this is a valid guest request next.ServeHTTP(w, r) }) } func AuthSession(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // if session key exists then this is a valid auth request if v := r.Context().Value(SessionCtxKey("session")); v != nil { next.ServeHTTP(w, r) return } // else this is a guest session request, redirect to login http.Redirect(w, r, "/u/auth", http.StatusSeeOther) }) }