dndex/server/middleware.go

50 lines
1007 B
Go

package server
import (
"io"
"local/dndex/config"
"local/dndex/server/auth"
"local/gziphttp"
"net/http"
"time"
)
func (rest *REST) delay(foo http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
select {
case <-time.After(config.New().Delay):
foo(w, r)
case <-r.Context().Done():
http.Error(w, r.Context().Err().Error(), 499)
}
}
}
func (rest *REST) defend(foo http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if gziphttp.Can(r) {
gz := gziphttp.New(w)
defer gz.Close()
w = gz
}
r.Body = struct {
io.Reader
io.Closer
}{
Reader: io.LimitReader(r.Body, config.New().MaxFileSize),
Closer: r.Body,
}
foo(w, r)
}
}
func (rest *REST) auth(foo http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if err := auth.Verify(rest.g, w, r); err != nil {
http.Error(w, err.Error(), http.StatusUnauthorized)
return
}
foo(w, r)
}
}