1
0
Fork 0
httpserver/middleware/middleware.go

61 Zeilen
1.5 KiB
Go

package middleware
import (
"net/http"
"time"
"github.com/gin-gonic/gin"
"github.com/phuslu/log"
"go.sebtobie.de/httpserver"
"go.sebtobie.de/httpserver/auth"
)
// LogMiddleware is an middleware to log requests to phuslu/log and catches panics.
// If it is added multiple times, only the first time sends entries to the log.
func LogMiddleware(c *gin.Context) {
if _, exists := c.Get("xid"); exists {
return
}
var xid = log.NewXIDWithTime(time.Now().UnixNano())
c.Set("xid", xid)
defer func() {
var entry *log.Entry
interrupt := recover()
if interrupt != nil {
err := interrupt.(error)
c.Header("requestid", xid.String())
c.AbortWithStatus(http.StatusInternalServerError)
entry = log.Error().Err(err).Int("statuscode", 500)
} else {
statuscode := c.Writer.Status()
switch {
case statuscode >= 400 && statuscode < 500:
entry = log.Warn()
case statuscode >= 500:
entry = log.Error()
default:
entry = log.Info()
}
entry.Int("statuscode", statuscode)
}
entry.Int64("goroutine", log.Goid()).Xid("ID", xid).Msg("Request")
}()
c.Next()
}
// RequireUser is an middleware that looks if the user is an Anonymous user and redircts it to the login if so.
func RequireUser(c *gin.Context) {
var acc = c.MustGet(httpserver.Accounts).(auth.Account)
if acc.Anonymous() {
acc.Redirect(c)
c.Abort()
return
}
}
// Middleware is an type to Save data between executions and to provide help at the teardown.
type Middleware interface {
Gin(*gin.Context)
Teardown()
}