middleware.go 1.11 KB
package webutility

import (
	"net/http"
	"time"

	"git.to-net.rs/marko.tikvic/gologger"
)

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)
	}
}

var reqLogger *gologger.Logger

func EnableLogging(log string) error {
	var err error
	reqLogger, err = gologger.New(log, gologger.MaxLogSize5MB)
	return err
}

func Log(h http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, req *http.Request) {
		reqLogger.LogRequest(req, "")
		t1 := time.Now()
		h(w, req)
		t2 := time.Now()
		reqLogger.LogResponse(w, t2.Sub(t1))
	}
}

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