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.Info() int := recover() if int != nil { err := int.(error) c.Header("requestid", xid.String()) c.AbortWithStatus(http.StatusInternalServerError) entry = log.Error().Err(err).Int("statuscode", 500) } else { statuscode := c.Writer.Status() if statuscode >= 400 { entry = log.Error() } entry = 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() }