app/server/middleware.go

65 lines
1.3 KiB
Go
Raw Normal View History

2021-12-16 04:11:33 +00:00
package server
import (
"fmt"
"net"
"time"
"github.com/gin-gonic/gin"
"github.com/rs/zerolog"
"kumoly.io/kumoly/app/errors"
2021-12-19 10:52:40 +00:00
"kumoly.io/kumoly/app/util"
2021-12-16 04:11:33 +00:00
)
func (srv *Service) Default(c *gin.Context) {
path := c.Request.URL.Path
start := time.Now()
defer func() {
var cl *zerolog.Event
err := recover()
if err != nil {
cl = srv.l.Error()
switch v := err.(type) {
case errors.Error:
c.AbortWithStatusJSON(v.Code, v)
cl.Err(v)
case error:
c.String(500, v.Error())
c.Abort()
cl.Err(v)
default:
c.String(500, fmt.Sprint(err))
c.Abort()
cl.Str("error", fmt.Sprint(err))
}
2021-12-19 10:52:40 +00:00
if !util.PROD {
2021-12-19 18:46:00 +00:00
cl.Caller(2)
// cl.Str("trace", util.Stack())
2021-12-19 10:52:40 +00:00
}
2021-12-19 06:53:36 +00:00
} else if c.Writer.Status() >= 400 {
2021-12-16 04:11:33 +00:00
cl = srv.l.Error().Strs("error", c.Errors.Errors())
} else {
cl = srv.l.Info()
}
if srv.SkipLog != nil && srv.SkipLog(c) {
return
}
2021-12-16 17:45:09 +00:00
if usr, ok := c.Get("user"); ok {
cl.Str("user", usr.(string))
}
2021-12-16 04:11:33 +00:00
cl.
Str("method", c.Request.Method).
Str("ip", c.ClientIP()).
Int("status", c.Writer.Status()).
Dur("duration", time.Since(start)).
Str("url", path).
Msg("")
}()
if srv.Allow != nil {
if !srv.Allow.Contains(net.ParseIP(c.ClientIP())) {
panic(errors.ErrorForbidden)
}
}
c.Next()
}