2019-05-14 14:11:03 +02:00
|
|
|
package web
|
|
|
|
|
|
|
|
import (
|
|
|
|
"net/http"
|
|
|
|
"net/rpc"
|
|
|
|
"strings"
|
|
|
|
|
2019-12-14 07:28:33 +01:00
|
|
|
scs "github.com/alexedwards/scs/v2"
|
2019-05-14 14:11:03 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
// 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)
|
|
|
|
}
|
|
|
|
}
|