middleware.go 1.63 KB
package webutility

import (
	"net/http"
	"time"

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

var httpLogger *gologger.Logger

// SetHeaders ...
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)
	}
}

// ParseForm ...
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)
	}
}

// ParseMultipartForm ...
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)
	}
}

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

// Log ...
func Log(h http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, req *http.Request) {
		t1 := time.Now()

		claims, _ := GetTokenClaims(req)
		in := httpLogger.LogHTTPRequest(req, claims.Username)

		rec := NewStatusRecorder(w)

		h(rec, req)

		t2 := time.Now()
		out := httpLogger.LogHTTPResponse(rec.Status(), t2.Sub(t1), rec.Size())

		httpLogger.CombineHTTPLogs(in, out)
	}
}

// Auth ...
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)
	}
}