dndex/server/middleware.go

81 lines
1.7 KiB
Go

package server
import (
"io"
"local/dndex/config"
"local/dndex/server/auth"
"local/gziphttp"
"net/http"
"path"
"strings"
"time"
)
func (rest *REST) scoped(foo http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
rest.scope(r)
foo(w, r)
}
}
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)
}
}
func (rest *REST) shift(foo http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
i := 1
for i < len(r.URL.Path) && r.URL.Path[i] != '/' {
i++
}
r.URL.Path = r.URL.Path[i:]
if !strings.HasPrefix(r.URL.Path, "/") {
r.URL.Path = "/" + r.URL.Path
}
foo(w, r)
}
}
func (rest *REST) deprefix(foo http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
newpath := strings.TrimPrefix(r.URL.Path, path.Join("/", config.New().APIPrefix))
r.URL.Path = newpath
foo(w, r)
}
}