app/server/middleware.go

57 lines
1.1 KiB
Go
Raw Permalink 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"
)
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))
}
} else if c.Writer.Status() >= 500 {
cl = srv.l.Error().Strs("error", c.Errors.Errors())
} else {
cl = srv.l.Info()
}
if srv.SkipLog != nil && srv.SkipLog(c) {
return
}
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()
}