chore: stabilize lint and verify builds

This commit is contained in:
2026-02-06 11:51:32 +08:00
parent edede17880
commit 1782f64417
114 changed files with 3032 additions and 1345 deletions

View File

@@ -9,7 +9,7 @@ import (
"strings"
"time"
log "github.com/sirupsen/logrus"
logrus "github.com/sirupsen/logrus"
"go.ipao.vip/atom/container"
"go.ipao.vip/atom/opt"
@@ -40,22 +40,25 @@ type Service struct {
Engine *fiber.App
}
var errTLSCertKeyRequired = errors.New("tls cert and key must be set")
func (svc *Service) listenerConfig() fiber.ListenConfig {
listenConfig := fiber.ListenConfig{
EnablePrintRoutes: true,
// DisableStartupMessage: true,
}
if svc.conf.Tls != nil {
if svc.conf.Tls.Cert == "" || svc.conf.Tls.Key == "" {
panic(errors.New("tls cert and key must be set"))
if svc.conf.TLS != nil {
if svc.conf.TLS.Cert == "" || svc.conf.TLS.Key == "" {
panic(errTLSCertKeyRequired)
}
listenConfig.CertFile = svc.conf.Tls.Cert
listenConfig.CertKeyFile = svc.conf.Tls.Key
listenConfig.CertFile = svc.conf.TLS.Cert
listenConfig.CertKeyFile = svc.conf.TLS.Key
}
container.AddCloseAble(func() {
svc.Engine.ShutdownWithTimeout(time.Second * 10)
})
return listenConfig
}
@@ -64,8 +67,6 @@ func (svc *Service) Listener(ln net.Listener) error {
}
func (svc *Service) Serve(ctx context.Context) error {
// log.WithField("http_address", svc.conf.Address()).Info("http config address")
ln, err := net.Listen("tcp4", svc.conf.Address())
if err != nil {
return err
@@ -109,15 +110,13 @@ func Provide(opts ...opt.Option) error {
EnableIPValidation: true,
})
// request id first for correlation
engine.Use(requestid.New())
// recover with stack + request id
engine.Use(recover.New(recover.Config{
EnableStackTrace: true,
StackTraceHandler: func(c fiber.Ctx, e any) {
rid := c.Get(fiber.HeaderXRequestID)
log.WithField("request_id", rid).Error(fmt.Sprintf("panic: %v\n%s\n", e, debug.Stack()))
logrus.WithField("request_id", rid).Error(fmt.Sprintf("panic: %v\n%s\n", e, debug.Stack()))
},
}))
@@ -133,9 +132,7 @@ func Provide(opts ...opt.Option) error {
}
}
// logging with request id and latency
engine.Use(logger.New(logger.Config{
// requestid middleware stores ctx.Locals("requestid")
Format: `${time} [${ip}] ${method} ${status} ${path} ${latency} rid=${locals:requestid} "${ua}"\n`,
TimeFormat: time.RFC3339,
TimeZone: "Asia/Shanghai",
@@ -143,9 +140,9 @@ func Provide(opts ...opt.Option) error {
// rate limit (by tenant code or IP)
if config.RateLimit != nil && config.RateLimit.Enabled {
max := config.RateLimit.Max
if max <= 0 {
max = 120
limitMax := config.RateLimit.Max
if limitMax <= 0 {
limitMax = 120
}
windowSeconds := config.RateLimit.WindowSeconds
if windowSeconds <= 0 {
@@ -165,7 +162,7 @@ func Provide(opts ...opt.Option) error {
skipPrefixes := append([]string{"/healthz", "/readyz"}, config.RateLimit.SkipPaths...)
engine.Use(limiter.New(limiter.Config{
Max: max,
Max: limitMax,
Expiration: time.Duration(windowSeconds) * time.Second,
Storage: limiterStorage,
LimitReached: func(c fiber.Ctx) error {
@@ -173,10 +170,11 @@ func Provide(opts ...opt.Option) error {
if message != "" {
appErr = appErr.WithMsg(message)
}
return errorx.SendError(c, appErr)
},
Next: func(c fiber.Ctx) bool {
path := c.Path()
Next: func(requestCtx fiber.Ctx) bool {
path := requestCtx.Path()
for _, prefix := range skipPrefixes {
if prefix == "" {
continue
@@ -185,31 +183,30 @@ func Provide(opts ...opt.Option) error {
return true
}
}
return false
},
KeyGenerator: func(c fiber.Ctx) string {
if strings.HasPrefix(c.Path(), "/t/") {
if tenantCode := strings.TrimSpace(c.Params("tenantCode")); tenantCode != "" {
KeyGenerator: func(requestCtx fiber.Ctx) string {
if strings.HasPrefix(requestCtx.Path(), "/t/") {
if tenantCode := strings.TrimSpace(requestCtx.Params("tenantCode")); tenantCode != "" {
return "tenant:" + tenantCode
}
}
return c.IP()
return requestCtx.IP()
},
}))
}
// static files (Fiber v3 Static helper moved; enable via filesystem middleware later)
// if config.StaticRoute != nil && config.StaticPath != nil { ... }
// health endpoints
engine.Get("/healthz", func(c fiber.Ctx) error { return c.SendStatus(fiber.StatusNoContent) })
engine.Get("/readyz", func(c fiber.Ctx) error { return c.SendStatus(fiber.StatusNoContent) })
engine.Hooks().OnPostShutdown(func(err error) error {
if err != nil {
log.Error("http server shutdown error: ", err)
logrus.Error("http server shutdown error: ", err)
}
log.Info("http server has shutdown success")
logrus.Info("http server has shutdown success")
return nil
})
@@ -235,20 +232,20 @@ func buildCORSConfig(c *Cors) *cors.Config {
exposes []string
allowCreds bool
)
for _, w := range c.Whitelist {
if w.AllowOrigin != "" {
origins = append(origins, w.AllowOrigin)
for _, whitelistItem := range c.Whitelist {
if whitelistItem.AllowOrigin != "" {
origins = append(origins, whitelistItem.AllowOrigin)
}
if w.AllowHeaders != "" {
headers = append(headers, w.AllowHeaders)
if whitelistItem.AllowHeaders != "" {
headers = append(headers, whitelistItem.AllowHeaders)
}
if w.AllowMethods != "" {
methods = append(methods, w.AllowMethods)
if whitelistItem.AllowMethods != "" {
methods = append(methods, whitelistItem.AllowMethods)
}
if w.ExposeHeaders != "" {
exposes = append(exposes, w.ExposeHeaders)
if whitelistItem.ExposeHeaders != "" {
exposes = append(exposes, whitelistItem.ExposeHeaders)
}
allowCreds = allowCreds || w.AllowCredentials
allowCreds = allowCreds || whitelistItem.AllowCredentials
}
cfg := cors.Config{
@@ -258,5 +255,6 @@ func buildCORSConfig(c *Cors) *cors.Config {
ExposeHeaders: lo.Uniq(exposes),
AllowCredentials: allowCreds,
}
return &cfg
}