Skip to content

上下文辅助函数

VEF Framework 的 contextx 包提供了一组辅助函数,用于在请求上下文中存取数据。

获取当前用户

go
import "github.com/ilxqx/vef-framework-go/contextx"

func (r *UserResource) GetProfile(ctx fiber.Ctx) error {
    // Get current authenticated user
    currentUser := contextx.GetCurrentUser(ctx)
    
    // Access user properties
    userId := currentUser.Id
    username := currentUser.Username
    roles := currentUser.RoleIds
    permissions := currentUser.Permissions
    
    return api.Success(ctx, currentUser)
}

获取请求信息

go
// Get request ID
requestId := contextx.GetRequestId(ctx)

// Get client IP
clientIP := contextx.GetClientIP(ctx)

// Get user agent
userAgent := contextx.GetUserAgent(ctx)

// Get request path
path := contextx.GetPath(ctx)

// Get request method
method := contextx.GetMethod(ctx)

获取租户信息

go
// Get current tenant ID
tenantId := contextx.GetTenantId(ctx)

// Get tenant info
tenant := contextx.GetTenant(ctx)

自定义上下文数据

设置数据

go
// Set custom data
ctx.Locals("customKey", "customValue")

// Set struct data
ctx.Locals("orderInfo", &OrderInfo{
    OrderId: "order-001",
    Amount:  100.00,
})

获取数据

go
// Get string value
value := ctx.Locals("customKey").(string)

// Get struct value
orderInfo := ctx.Locals("orderInfo").(*OrderInfo)

// Safe type assertion
if value, ok := ctx.Locals("customKey").(string); ok {
    // Use value
}

数据库上下文

go
// Get database connection from context
db := contextx.GetDB(ctx)

// Use in transaction
tx := contextx.GetTx(ctx)
if tx != nil {
    // In transaction
    tx.Create(&model)
} else {
    // Not in transaction
    db.Create(&model)
}

用户权限检查

go
currentUser := contextx.GetCurrentUser(ctx)

// Check single permission
if currentUser.HasPermission("user:delete") {
    // Can delete users
}

// Check any permission
if currentUser.HasAnyPermission("admin:manage", "super:admin") {
    // Has admin access
}

// Check all permissions
if currentUser.HasAllPermissions("order:read", "order:update") {
    // Can read and update orders
}

// Check role
if currentUser.HasRole("admin") {
    // Is admin
}

请求追踪

go
// Get trace context
traceId := contextx.GetTraceId(ctx)
spanId := contextx.GetSpanId(ctx)

// Log with trace context
log.WithFields(log.Fields{
    "traceId": traceId,
    "spanId":  spanId,
}).Info("Processing request")

语言和时区

go
// Get request language
lang := contextx.GetLanguage(ctx) // e.g., "zh-CN"

// Get timezone
timezone := contextx.GetTimezone(ctx) // e.g., "Asia/Shanghai"

// Get location
loc, _ := time.LoadLocation(timezone)
localTime := time.Now().In(loc)

完整示例

go
package resources

import (
    "github.com/ilxqx/vef-framework-go/api"
    "github.com/ilxqx/vef-framework-go/contextx"
    "github.com/gofiber/fiber/v2"
)

type OrderResource struct {
    api.Resource
}

func (r *OrderResource) CreateOrder(ctx fiber.Ctx, params CreateOrderParams) error {
    // Get current user
    currentUser := contextx.GetCurrentUser(ctx)
    
    // Check permission
    if !currentUser.HasPermission("order:create") {
        return api.Forbidden(ctx, "Permission denied")
    }
    
    // Get request context
    requestId := contextx.GetRequestId(ctx)
    clientIP := contextx.GetClientIP(ctx)
    
    // Create order with context data
    order := &models.Order{
        UserId:    currentUser.Id,
        TenantId:  contextx.GetTenantId(ctx),
        Amount:    params.Amount,
        CreatedBy: currentUser.Id,
        CreatedIP: clientIP,
    }
    
    if err := orm.DB().Create(order).Error; err != nil {
        log.WithField("requestId", requestId).Error("Failed to create order:", err)
        return api.Error(ctx, "Failed to create order")
    }
    
    return api.Success(ctx, order)
}

下一步

基于 Apache License 2.0 许可发布