2019-06-06 13:06:31 +02:00
|
|
|
package http
|
|
|
|
|
2019-07-06 15:10:39 +02:00
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"errors"
|
|
|
|
"net/http"
|
|
|
|
)
|
2019-06-06 13:06:31 +02:00
|
|
|
|
2019-07-06 16:05:27 +02:00
|
|
|
// CorsMiddleware ensures the wrapped handler will respond with proper CORS
|
|
|
|
// headers using the given origin.
|
2019-07-06 15:10:39 +02:00
|
|
|
func CorsMiddleware(origin string) func(http.Handler) http.Handler {
|
|
|
|
return func(next http.Handler) http.Handler {
|
|
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
|
|
w.Header().Set("Access-Control-Allow-Credentials", "true")
|
|
|
|
w.Header().Set("Access-Control-Allow-Methods", "POST,GET")
|
|
|
|
w.Header().Set("Access-Control-Allow-Origin", origin)
|
|
|
|
next.ServeHTTP(w, r)
|
|
|
|
})
|
|
|
|
}
|
2019-06-06 13:06:31 +02:00
|
|
|
}
|
|
|
|
|
2019-07-06 16:05:27 +02:00
|
|
|
// ContentTypeMiddleware ensuresthe wrapped handler will respond with a
|
|
|
|
// content type header of the given value.
|
2019-07-06 15:10:39 +02:00
|
|
|
func ContentTypeMiddleware(contentType string) func(http.Handler) http.Handler {
|
|
|
|
return func(next http.Handler) http.Handler {
|
|
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
|
|
w.Header().Add("Content-Type", contentType)
|
|
|
|
next.ServeHTTP(w, r)
|
|
|
|
})
|
|
|
|
}
|
2019-06-06 13:06:31 +02:00
|
|
|
}
|
|
|
|
|
2019-07-06 16:05:27 +02:00
|
|
|
// OptoutMiddleware drops all requests to the given handler that are sent with
|
|
|
|
// a cookie of the given name,
|
2019-07-06 15:10:39 +02:00
|
|
|
func OptoutMiddleware(cookieName string) func(http.Handler) http.Handler {
|
|
|
|
return func(next http.Handler) http.Handler {
|
|
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
|
|
if _, err := r.Cookie(cookieName); err == nil {
|
|
|
|
w.WriteHeader(http.StatusNoContent)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
next.ServeHTTP(w, r)
|
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-07-06 16:05:27 +02:00
|
|
|
// UserCookieMiddleware ensures a cookie of the given name is present and
|
|
|
|
// attaches its value to the request's context using the given key, before
|
|
|
|
// passing it on to the wrapped handler.
|
2019-07-06 15:10:39 +02:00
|
|
|
func UserCookieMiddleware(cookieKey string, contextKey interface{}) func(http.Handler) http.Handler {
|
|
|
|
return func(next http.Handler) http.Handler {
|
|
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
|
|
c, err := r.Cookie(cookieKey)
|
|
|
|
if err != nil {
|
2019-07-06 16:05:27 +02:00
|
|
|
RespondWithJSONError(w, errors.New("received no or blank user identifier"), http.StatusBadRequest)
|
2019-07-06 15:10:39 +02:00
|
|
|
return
|
|
|
|
}
|
|
|
|
r = r.WithContext(
|
|
|
|
context.WithValue(r.Context(), contextKey, c.Value),
|
|
|
|
)
|
|
|
|
next.ServeHTTP(w, r)
|
|
|
|
})
|
|
|
|
}
|
2019-06-06 13:06:31 +02:00
|
|
|
}
|