1
0
Fork 0
httpserver/middleware/middleware.go

50 Zeilen
1.2 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.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
}
}