package web import ( "net/http" "net/rpc" "strings" "github.com/alexedwards/scs" ) // GRPCMiddleware allows a HTTP2 Server to also serve GRPC at the same port. // Note that a valid certificate is needed, as HTTP2 requires TLS. func GRPCMiddleware(rpcServer *rpc.Server) func(next http.Handler) http.Handler { return func(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { ct := r.Header.Get("Content-Type") if r.ProtoMajor == 2 && strings.Contains(ct, "application/grpc") { rpcServer.ServeHTTP(w, r) } else { next.ServeHTTP(w, r) } }) } } // requireLogin makes sure a user is logged in, prior to access // to a certain ressource. func requireLogin(sess *scs.Session) func(http.Handler) http.Handler { return func(next http.Handler) http.Handler { handler := func(w http.ResponseWriter, r *http.Request) { if sess.GetString(r.Context(), SessKeyUserID) == "" { sess.Put(r.Context(), SessKeyNext, r.RequestURI) http.Redirect(w, r, "/login", http.StatusFound) return } next.ServeHTTP(w, r) return } return http.HandlerFunc(handler) } }