1
0
Fork 0
httpserver/middleware/middleware.go

61 Zeilen
1.5 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-23 23:43:31 +00:00
"go.sebtobie.de/httpserver"
2021-01-18 23:13:35 +00:00
"go.sebtobie.de/httpserver/auth"
2021-01-09 20:39:05 +00:00
)
2021-01-18 23:18:08 +00:00
// 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.
2021-01-09 20:39:05 +00:00
func LogMiddleware(c *gin.Context) {
2021-01-18 23:18:08 +00:00
if _, exists := c.Get("xid"); exists {
return
2021-01-09 20:39:05 +00:00
}
2021-01-18 23:18:08 +00:00
var xid = log.NewXIDWithTime(time.Now().UnixNano())
c.Set("xid", xid)
2021-01-09 20:39:05 +00:00
defer func() {
var entry *log.Entry
interrupt := recover()
if interrupt != nil {
err := interrupt.(error)
2021-01-09 20:39:05 +00:00
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()
switch {
case statuscode >= 400 && statuscode < 500:
entry = log.Warn()
case statuscode >= 500:
2021-01-09 20:39:05 +00:00
entry = log.Error()
default:
entry = log.Info()
2021-01-09 20:39:05 +00:00
}
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) {
2021-01-23 23:43:31 +00:00
var acc = c.MustGet(httpserver.Accounts).(auth.Account)
2021-01-18 23:13:35 +00:00
if acc.Anonymous() {
acc.Redirect(c)
c.Abort()
2021-01-18 23:13:35 +00:00
return
}
}
// Middleware is an type to Save data between executions and to provide help at the teardown.
type Middleware interface {
Gin(*gin.Context)
Teardown()
}