feat 错误包装
This commit is contained in:
@@ -28,9 +28,11 @@ func ginLogger(logger *zap.SugaredLogger) gin.HandlerFunc {
|
||||
path := c.Request.URL.Path
|
||||
c.Next()
|
||||
cost := time.Since(start)
|
||||
usn, _ := c.Get("usn")
|
||||
|
||||
logger.Infof(fmt.Sprintf(
|
||||
"HTTP Method:%v Code:%v Time:%v IP:%v Path:%v",
|
||||
"[usn:%v] Method:%v Code:%v Time:%v IP:%v Path:%v",
|
||||
usn,
|
||||
c.Request.Method,
|
||||
c.Writer.Status(),
|
||||
cost,
|
||||
@@ -45,6 +47,7 @@ func authJwt() gin.HandlerFunc {
|
||||
pList := strings.SplitN(c.Request.URL.Path, "/", 4)
|
||||
if len(pList) < 4 || pList[2] == "" {
|
||||
http_resp.JsonNotFound(c)
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
// 如果是Public接口,有Token就读,没有就算了
|
||||
@@ -69,6 +72,8 @@ func authJwt() gin.HandlerFunc {
|
||||
|
||||
// 这里将Header写到请求中,grpc-gateway框架会读取然后传给grpc服务
|
||||
c.Request.Header.Set("X-Usn", claims.USN)
|
||||
// 这里写到上下文中,打日志
|
||||
c.Set("usn", claims.USN)
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ package http_gateway
|
||||
|
||||
import (
|
||||
"context"
|
||||
"git.hlsq.asia/mmorpg/service-common/discover/common"
|
||||
"git.hlsq.asia/mmorpg/service-common/log"
|
||||
"git.hlsq.asia/mmorpg/service-common/net/grpc/grpc_client"
|
||||
"git.hlsq.asia/mmorpg/service-common/net/http/http_resp"
|
||||
@@ -11,6 +12,7 @@ import (
|
||||
"github.com/gin-contrib/cors"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
|
||||
"go.opentelemetry.io/contrib/instrumentation/github.com/gin-gonic/gin/otelgin"
|
||||
"google.golang.org/protobuf/encoding/protojson"
|
||||
)
|
||||
|
||||
@@ -47,6 +49,7 @@ func InitRouter() *gin.Engine {
|
||||
gin.Recovery(),
|
||||
ginLogger(log.GetLogger().Named("GIN")),
|
||||
cors.New(corsConfig()),
|
||||
otelgin.Middleware(common.KeyDiscoverServiceNameGateway),
|
||||
)
|
||||
|
||||
r.HandleMethodNotAllowed = true
|
||||
|
||||
@@ -33,11 +33,12 @@ func ErrorHandler(_ context.Context, _ *runtime.ServeMux, _ runtime.Marshaler, w
|
||||
code = http_resp.Failed.Code()
|
||||
msg = http_resp.Failed.Error()
|
||||
}
|
||||
if st.Code() == codes.Unknown ||
|
||||
st.Code() == codes.Unimplemented ||
|
||||
st.Code() == codes.NotFound {
|
||||
if st.Code() == codes.Unknown || st.Code() == codes.Unimplemented || st.Code() == codes.NotFound {
|
||||
msg = st.Message()
|
||||
}
|
||||
if st.Code() == codes.NotFound {
|
||||
code = http_resp.NotFound.Code()
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(grpcCodeToHTTPCode(st.Code()))
|
||||
|
||||
Reference in New Issue
Block a user