feat 包命名规范
This commit is contained in:
81
internal/net/httpgateway/middleward.go
Normal file
81
internal/net/httpgateway/middleward.go
Normal file
@@ -0,0 +1,81 @@
|
||||
package httpgateway
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"git.hlsq.asia/mmorpg/service-common/db/redis"
|
||||
"git.hlsq.asia/mmorpg/service-common/net/http/httpresp"
|
||||
"git.hlsq.asia/mmorpg/service-common/utils"
|
||||
"git.hlsq.asia/mmorpg/service-gateway/internal/global"
|
||||
"github.com/gin-contrib/cors"
|
||||
"github.com/gin-gonic/gin"
|
||||
"go.uber.org/zap"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
func corsConfig() cors.Config {
|
||||
return cors.Config{
|
||||
AllowMethods: []string{"GET", "POST", "OPTIONS"},
|
||||
AllowHeaders: []string{"Content-Type", "Authorization"},
|
||||
AllowCredentials: false,
|
||||
AllowAllOrigins: true,
|
||||
MaxAge: 12 * time.Hour,
|
||||
}
|
||||
}
|
||||
|
||||
func ginLogger(logger *zap.SugaredLogger) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
start := time.Now()
|
||||
path := c.Request.URL.Path
|
||||
c.Next()
|
||||
cost := time.Since(start)
|
||||
usn, _ := c.Get("usn")
|
||||
|
||||
logger.Infof(fmt.Sprintf(
|
||||
"[usn:%v] Method:%v Code:%v Time:%v IP:%v Path:%v",
|
||||
usn,
|
||||
c.Request.Method,
|
||||
c.Writer.Status(),
|
||||
cost,
|
||||
c.ClientIP(),
|
||||
path),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
func authJwt() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
pList := strings.SplitN(c.Request.URL.Path, "/", 4)
|
||||
if len(pList) < 4 || pList[2] == "" {
|
||||
httpresp.JsonNotFound(c)
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
// 如果是Public接口,有Token就读,没有就算了
|
||||
public := pList[2] == "open"
|
||||
|
||||
token := strings.TrimPrefix(c.GetHeader("Authorization"), "Bearer ")
|
||||
if token == "" {
|
||||
if public {
|
||||
c.Next()
|
||||
return
|
||||
}
|
||||
httpresp.JsonUnauthorized(c)
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
usn, _ := redis.GetClient().HGet(c, global.KeyGatewayAccessToken+token, (&utils.UserSession{}).GetUsnKey()).Int64()
|
||||
if usn == 0 {
|
||||
httpresp.JsonUnauthorized(c)
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
// 这里将Header写到请求中,grpc-gateway框架会读取然后传给grpc服务
|
||||
c.Request.Header.Set("X-Usn", utils.Int64ToString(usn))
|
||||
// 这里写到上下文中,打日志
|
||||
c.Set("usn", usn)
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user