middleware.go 958 Bytes
package webutility

import (
	"net/http"
)

func SetHeaders(h http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, req *http.Request) {
		SetDefaultHeaders(w)
		if req.Method == http.MethodOptions {
			return
		}
		h(w, req)
	}
}

func ParseForm(h http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, req *http.Request) {
		err := req.ParseForm()
		if err != nil {
			BadRequest(w, req, err.Error())
			return
		}
		h(w, req)
	}
}

func ParseMultipartForm(h http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, req *http.Request) {
		err := req.ParseMultipartForm(32 << 20)
		if err != nil {
			BadRequest(w, req, err.Error())
			return
		}
		h(w, req)
	}
}

func Auth(roles string, h http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, req *http.Request) {
		if _, err := AuthCheck(req, roles); err != nil {
			Unauthorized(w, req, err.Error())
			return
		}
		h(w, req)
	}
}