This repository has been archived on 2023-11-13. You can view files and clone it, but cannot push or open issues or pull requests.
imagini/routes/middlewares.go

41 lines
850 B
Go
Raw Normal View History

2021-01-06 19:36:09 +00:00
package routes
import (
"net/http"
"log"
"os"
)
2021-01-08 02:45:59 +00:00
type Middleware func(http.Handler) http.Handler
2021-01-06 19:36:09 +00:00
2021-01-08 02:45:59 +00:00
func MultipleMiddleware(h http.Handler, m ...Middleware) http.Handler {
2021-01-06 19:36:09 +00:00
if len(m) < 1 {
return h
}
wrapped := h
for i := len(m) - 1; i >= 0; i-- {
wrapped = m[i](wrapped)
}
return wrapped
}
2021-01-08 02:45:59 +00:00
func authMiddleware(h http.Handler) http.Handler {
2021-01-06 19:36:09 +00:00
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
2021-01-08 02:45:59 +00:00
_, ok := ValidateUserToken(r)
if ok {
next.ServeHTTP(w, r)
} else {
w.WriteHeader(http.StatusUnauthorized)
}
2021-01-06 19:36:09 +00:00
})
}
2021-01-08 02:45:59 +00:00
func logMiddleware(h http.Handler) http.Handler {
2021-01-06 19:36:09 +00:00
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.SetOutput(os.Stdout)
log.Println(r.Method, r.URL)
h.ServeHTTP(w, r)
})
}