skeleton/internal/web/middleware.go
2019-05-14 14:11:03 +02:00

42 lines
1.1 KiB
Go

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)
}
}