feat(tenant): 增加租户基础与域名解析
This commit is contained in:
@@ -0,0 +1,67 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
|
||||
"hfb_sys/backend/internal/config"
|
||||
"hfb_sys/backend/internal/sitecode"
|
||||
"hfb_sys/backend/internal/tenancy"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
const (
|
||||
ContextTenantID = "tenant_id"
|
||||
ContextTenantCode = "tenant_code"
|
||||
tenantCodeHeader = "X-Tenant-Code"
|
||||
)
|
||||
|
||||
type TenantResolver interface {
|
||||
ResolveHost(ctx context.Context, host string) (*tenancy.Scope, error)
|
||||
ResolveCode(ctx context.Context, code string) (*tenancy.Scope, error)
|
||||
}
|
||||
|
||||
func TenantContext(resolver TenantResolver, appEnv string, logger *zap.Logger) gin.HandlerFunc {
|
||||
if resolver == nil {
|
||||
return func(c *gin.Context) { c.Next() }
|
||||
}
|
||||
production := config.IsProductionEnv(appEnv)
|
||||
return func(c *gin.Context) {
|
||||
var (
|
||||
scope *tenancy.Scope
|
||||
err error
|
||||
)
|
||||
if !production {
|
||||
code := strings.TrimSpace(firstNonEmpty(c.GetHeader(tenantCodeHeader), c.Query("tenant_code")))
|
||||
if code != "" {
|
||||
scope, err = resolver.ResolveCode(c.Request.Context(), code)
|
||||
}
|
||||
}
|
||||
if scope == nil && err == nil {
|
||||
scope, err = resolver.ResolveHost(c.Request.Context(), c.Request.Host)
|
||||
}
|
||||
if err != nil && logger != nil {
|
||||
logger.Warn("经营租户解析失败,按旧站点上下文继续",
|
||||
zap.String("host", sitecode.ExtractHost(c.Request.Host)),
|
||||
zap.Error(err),
|
||||
)
|
||||
}
|
||||
if scope != nil {
|
||||
c.Request = c.Request.WithContext(tenancy.WithScope(c.Request.Context(), *scope))
|
||||
c.Set(ContextTenantID, scope.TenantID)
|
||||
c.Set(ContextTenantCode, scope.TenantCode)
|
||||
}
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
func firstNonEmpty(values ...string) string {
|
||||
for _, value := range values {
|
||||
if trimmed := strings.TrimSpace(value); trimmed != "" {
|
||||
return trimmed
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
Reference in New Issue
Block a user