提交 555bac62 authored 作者: mooncake9527's avatar mooncake9527

update

上级 85c45167
......@@ -3,6 +3,10 @@ app:
env: "dev"
version: "v0.0.1"
host: "0.0.0.0"
middleware:
cors: false # true or false
requestID:
key: trace-id # string or empty
enableStat: false
enableMetrics: true
enableHTTPProfile: true
......
......@@ -215,6 +215,7 @@ type Email struct {
type App struct {
CacheType string `yaml:"cacheType" json:"cacheType"`
Middleware Middleware `yaml:"middleware" json:"middleware"`
EnableCircuitBreaker bool `yaml:"enableCircuitBreaker" json:"enableCircuitBreaker"`
EnableHTTPProfile bool `yaml:"enableHTTPProfile" json:"enableHTTPProfile"`
EnableLimit bool `yaml:"enableLimit" json:"enableLimit"`
......@@ -237,6 +238,15 @@ type App struct {
IDGeneration IDGeneration `yaml:"idGeneration" json:"idGeneration"`
}
type Middleware struct {
Cors bool `yaml:"cors" json:"cors"`
RequestID RequestID `yaml:"requestID" json:"requestID"`
}
type RequestID struct {
Key string `yaml:"key" json:"key"`
}
type IDGeneration struct {
Type string `yaml:"type" json:"type"` // snowflake or leaf
Leaf Leaf `yaml:"leaf" json:"leaf"`
......
......@@ -2,4 +2,13 @@ package consts
var (
DefaultSchema string
RootRoute string
)
func SetDefaultSchema(schema string) {
DefaultSchema = schema
}
func SetRootRoute(v string) {
RootRoute = v
}
package xgin
import (
"fmt"
"net/http"
"time"
"github.com/gin-gonic/gin"
"github.com/gin-gonic/gin/binding"
"github.com/jinzhu/copier"
swaggerFiles "github.com/swaggo/files"
ginSwagger "github.com/swaggo/gin-swagger"
"gitlab.wanzhuangkj.com/tush/xpkg/config"
"gitlab.wanzhuangkj.com/tush/xpkg/consts"
"gitlab.wanzhuangkj.com/tush/xpkg/errcode"
"gitlab.wanzhuangkj.com/tush/xpkg/gin/handlerfunc"
"gitlab.wanzhuangkj.com/tush/xpkg/gin/middleware"
"gitlab.wanzhuangkj.com/tush/xpkg/gin/middleware/metrics"
"gitlab.wanzhuangkj.com/tush/xpkg/gin/prof"
"gitlab.wanzhuangkj.com/tush/xpkg/gin/validator"
"gitlab.wanzhuangkj.com/tush/xpkg/ips"
"gitlab.wanzhuangkj.com/tush/xpkg/jwt"
"gitlab.wanzhuangkj.com/tush/xpkg/logger"
"gitlab.wanzhuangkj.com/tush/xpkg/text"
"gitlab.wanzhuangkj.com/tush/xpkg/utils/webLogUtils"
xvalidator "gitlab.wanzhuangkj.com/tush/xpkg/xcommon/validator"
)
func New() *gin.Engine {
var app config.App
var auth config.Auth
var httpCfg config.HTTP
config.Read(func(c *config.Config) {
copier.Copy(&app, c.App)
copier.Copy(&httpCfg, c.HTTP)
copier.Copy(&auth, c.Auth)
})
r := gin.New()
r.Use(middleware.CustomRecoveryWithLogger(logger.Get()))
if app.Middleware.Cors {
r.Use(middleware.Cors())
}
gin.DefaultWriter = logger.GetZapWriter()
gin.DefaultErrorWriter = logger.GetZapWriter()
if httpCfg.Timeout > 0 {
r.Use(middleware.Timeout(time.Second * time.Duration(httpCfg.Timeout)))
}
if app.Middleware.RequestID.Key != "" {
r.Use(middleware.RequestID(middleware.WithHeaderRequestIDKey(app.Middleware.RequestID.Key)))
} else {
r.Use(middleware.RequestID())
}
r.Use(middleware.Logging(
middleware.WithAppName(app.Name),
middleware.WithMaxLen(8192),
middleware.WithLog(logger.Get()),
middleware.WithTraceIDFromContext(),
middleware.WithIgnoreRoutes("/metrics"), // ignore path
))
if auth.Enable {
jwt.Init(
jwt.WithExpire(auth.Expire),
jwt.WithSigningKey(auth.SignKey),
jwt.WithSigningMethod(jwt.HS256),
)
}
if app.EnableMetrics {
r.Use(metrics.Metrics(r,
metrics.WithIgnoreStatusCodes(http.StatusNotFound), // ignore 404 status codes
))
}
if app.EnableLimit {
r.Use(middleware.RateLimit())
}
if app.EnableCircuitBreaker {
r.Use(middleware.CircuitBreaker())
}
if app.EnableTrace {
r.Use(middleware.Tracing(app.Name))
}
if app.EnableHTTPProfile {
prof.Register(r, prof.WithIOWaitTime())
}
binding.Validator = validator.Init()
r.Use(xvalidator.Translation())
webLogUtils.Init(consts.DefaultSchema)
if config.IsNotProd() {
r.GET(consts.RootRoute+"/config", gin.WrapF(errcode.ShowConfig([]byte(config.Show()))))
r.GET(consts.RootRoute+"/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
defer func() {
fmt.Println(text.Blue(fmt.Sprintf("swagger: http://localhost:%d"+consts.RootRoute+"/swagger/index.html", httpCfg.Port)))
ip := ips.GetLocalHost()
if ip != "" {
fmt.Println(text.Blue(fmt.Sprintf("swagger: https://%s:%d"+consts.RootRoute+"/swagger/index.html", ip, httpCfg.Port)))
}
}()
}
r.GET("/health", handlerfunc.CheckHealth)
r.GET("/ping", handlerfunc.Ping)
r.GET("/codes", handlerfunc.ListCodes)
return r
}
func RegisterRouters(r *gin.Engine, groupPath string, routerFns []func(*gin.RouterGroup), middlewares ...gin.HandlerFunc) {
rg := r.Group(groupPath)
rg.Use(middlewares...)
for _, fn := range routerFns {
fn(rg)
}
}
......@@ -7,10 +7,12 @@ import (
"strings"
"time"
"gitlab.wanzhuangkj.com/tush/xpkg/config"
"gitlab.wanzhuangkj.com/tush/xpkg/database"
"gitlab.wanzhuangkj.com/tush/xpkg/xcommon/api"
"github.com/gin-gonic/gin"
"github.com/jinzhu/copier"
"github.com/spf13/cast"
"gitlab.wanzhuangkj.com/tush/xpkg/httpcli/entity"
"gitlab.wanzhuangkj.com/tush/xpkg/logger"
......@@ -24,15 +26,28 @@ import (
glogger "gorm.io/gorm/logger"
)
var (
enable bool = false
ignore = make(map[string]struct{})
)
func WebLogInterceptor() func(c *gin.Context) {
return func(c *gin.Context) {
if !enable {
c.Next()
return
}
URL := strings.ToLower(c.Request.Method) + "#" + c.Request.URL.Path
if _, ok := ignore[URL]; ok {
c.Next()
return
}
var (
req *entity.CopyHttpReq
rsp *entity.CopyHttpRsp
// respCode int
)
ctx := ctxUtils.WrapCtx(c)
URL := strings.ToLower(c.Request.Method) + "#" + c.Request.URL.Path
xApi, ok := api.XApi.M[URL]
if ok {
companyID := ctxUtils.GetCtxCompanyID(c)
......@@ -77,7 +92,19 @@ func GetUserID(ctx context.Context) xsf.ID {
var merger *merge.FanIn
func Init(schema string, isProd bool) {
func Init(schema string) {
var webLogCfg config.WebLog
config.IsProd()
config.Read(func(c *config.Config) {
copier.Copy(&webLogCfg, c.App.WebLog)
})
if !webLogCfg.Enable {
return
}
isProd := config.IsProd()
for _, p := range webLogCfg.IgnorePaths {
ignore[strings.TrimSpace(p)] = struct{}{}
}
duration := 10 * time.Minute
count := 256
if !isProd {
......@@ -114,6 +141,7 @@ func Init(schema string, isProd bool) {
}
}
}()
logger.Info("[webLog]init success")
return nil
})
......
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论