Moved to go 1.22 net/http
This commit is contained in:
17
middleware/auth.go
Normal file
17
middleware/auth.go
Normal file
@@ -0,0 +1,17 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func EnsureAdmin(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if !strings.Contains(r.Header.Get("Authorization"), "Admin") {
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
w.Write([]byte(http.StatusText(http.StatusUnauthorized)))
|
||||
return
|
||||
}
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
32
middleware/logging.go
Normal file
32
middleware/logging.go
Normal file
@@ -0,0 +1,32 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"log"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
type wrappedWriter struct {
|
||||
http.ResponseWriter
|
||||
statusCode int
|
||||
}
|
||||
|
||||
func (w *wrappedWriter) WriteHeader(statusCode int) {
|
||||
w.ResponseWriter.WriteHeader(statusCode)
|
||||
w.statusCode = statusCode
|
||||
}
|
||||
|
||||
func Logging(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
start := time.Now()
|
||||
|
||||
wrapped := &wrappedWriter{
|
||||
ResponseWriter: w,
|
||||
statusCode: http.StatusOK,
|
||||
}
|
||||
|
||||
next.ServeHTTP(wrapped, r)
|
||||
|
||||
log.Println(wrapped.statusCode, r.Method, r.URL.Path, time.Since(start))
|
||||
})
|
||||
}
|
||||
16
middleware/middleware.go
Normal file
16
middleware/middleware.go
Normal file
@@ -0,0 +1,16 @@
|
||||
package middleware
|
||||
|
||||
import "net/http"
|
||||
|
||||
type Middleware func(http.Handler) http.Handler
|
||||
|
||||
func CreateStack(xs ...Middleware) Middleware {
|
||||
return func(next http.Handler) http.Handler {
|
||||
for i := len(xs) - 1; i >= 0; i-- {
|
||||
x := xs[i]
|
||||
next = x(next)
|
||||
}
|
||||
|
||||
return next
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user