1
0
Fork 0
httpserver/middleware/middleware.go

51 Zeilen
1.2 KiB
Go

package middleware
2021-01-09 20:39:05 +00:00
import (
"net/http"
"time"
"github.com/gin-gonic/gin"
"github.com/phuslu/log"
2021-01-18 23:13:35 +00:00
"go.sebtobie.de/httpserver/auth"
2021-01-09 20:39:05 +00:00
)
2021-01-10 14:15:29 +00:00
// LogMiddleware is an middleware to log requests to phuslu/log and catches panics
2021-01-09 20:39:05 +00:00
func LogMiddleware(c *gin.Context) {
var xid log.XID
var tmp interface{}
var exists bool
if tmp, exists = c.Get("xid"); !exists {
xid = log.NewXIDWithTime(time.Now().UnixNano())
c.Set("xid", xid)
} else {
xid = tmp.(log.XID)
}
defer func() {
2021-01-10 14:15:29 +00:00
var entry = log.Info()
2021-01-09 20:39:05 +00:00
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 {
2021-01-10 14:15:29 +00:00
statuscode := c.Writer.Status()
if statuscode >= 400 {
2021-01-09 20:39:05 +00:00
entry = log.Error()
}
2021-01-10 14:15:29 +00:00
entry = entry.Int("statuscode", statuscode)
2021-01-09 20:39:05 +00:00
}
entry.Int64("goroutine", log.Goid()).Xid("ID", xid).Msg("Request")
}()
c.Next()
}
2021-01-18 23:13:35 +00:00
// 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("account").(auth.Account)
if acc.Anonymous() {
acc.Redirect(c)
return
}
}