init commit
This commit is contained in:
@@ -0,0 +1,104 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"log"
|
||||
"net/http"
|
||||
"slices"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/config"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// 无需认证的API列表
|
||||
var noAuthAPI = map[string][]string{
|
||||
"/api/v1/test-data": {"GET"},
|
||||
"/api/v1/tenants": {"POST"},
|
||||
}
|
||||
|
||||
// 检查请求是否在无需认证的API列表中
|
||||
func isNoAuthAPI(path string, method string) bool {
|
||||
for api, methods := range noAuthAPI {
|
||||
if api == path && slices.Contains(methods, method) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// Auth 认证中间件
|
||||
func Auth(tenantService interfaces.TenantService, cfg *config.Config) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
// ignore OPTIONS request
|
||||
if c.Request.Method == "OPTIONS" {
|
||||
c.Next()
|
||||
return
|
||||
}
|
||||
|
||||
// 检查请求是否在无需认证的API列表中
|
||||
if isNoAuthAPI(c.Request.URL.Path, c.Request.Method) {
|
||||
c.Next()
|
||||
return
|
||||
}
|
||||
|
||||
// Get API Key from request header
|
||||
apiKey := c.GetHeader("X-API-Key")
|
||||
if apiKey == "" {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized"})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
// Get tenant information
|
||||
tenantID, err := tenantService.ExtractTenantIDFromAPIKey(apiKey)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{
|
||||
"error": "Unauthorized: invalid API key format",
|
||||
})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
// Verify API key validity (matches the one in database)
|
||||
t, err := tenantService.GetTenantByID(c.Request.Context(), tenantID)
|
||||
if err != nil {
|
||||
log.Printf("Error getting tenant by ID: %v, tenantID: %d, apiKey: %s", err, tenantID, apiKey)
|
||||
c.JSON(http.StatusUnauthorized, gin.H{
|
||||
"error": "Unauthorized: invalid API key",
|
||||
})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
if t == nil || t.APIKey != apiKey {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{
|
||||
"error": "Unauthorized: invalid API key",
|
||||
})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
// Store tenant ID in context
|
||||
c.Set(types.TenantIDContextKey.String(), tenantID)
|
||||
c.Set(types.TenantInfoContextKey.String(), t)
|
||||
c.Request = c.Request.WithContext(
|
||||
context.WithValue(
|
||||
context.WithValue(c.Request.Context(), types.TenantIDContextKey, tenantID),
|
||||
types.TenantInfoContextKey, t,
|
||||
),
|
||||
)
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
// GetTenantIDFromContext helper function to get tenant ID from context
|
||||
func GetTenantIDFromContext(ctx context.Context) (uint, error) {
|
||||
tenantID, ok := ctx.Value("tenantID").(uint)
|
||||
if !ok {
|
||||
return 0, errors.New("tenant ID not found in context")
|
||||
}
|
||||
return tenantID, nil
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/errors"
|
||||
)
|
||||
|
||||
// ErrorHandler 是一个处理应用错误的中间件
|
||||
func ErrorHandler() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
// 处理请求
|
||||
c.Next()
|
||||
|
||||
// 检查是否有错误
|
||||
if len(c.Errors) > 0 {
|
||||
// 获取最后一个错误
|
||||
err := c.Errors.Last().Err
|
||||
|
||||
// 检查是否为应用错误
|
||||
if appErr, ok := errors.IsAppError(err); ok {
|
||||
// 返回应用错误
|
||||
c.JSON(appErr.HTTPCode, gin.H{
|
||||
"success": false,
|
||||
"error": gin.H{
|
||||
"code": appErr.Code,
|
||||
"message": appErr.Message,
|
||||
"details": appErr.Details,
|
||||
},
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// 处理其他类型的错误
|
||||
c.JSON(http.StatusInternalServerError, gin.H{
|
||||
"success": false,
|
||||
"error": gin.H{
|
||||
"code": errors.ErrInternalServer,
|
||||
"message": "Internal server error",
|
||||
},
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// RequestID middleware adds a unique request ID to the context
|
||||
func RequestID() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
// Get request ID from header or generate a new one
|
||||
requestID := c.GetHeader("X-Request-ID")
|
||||
if requestID == "" {
|
||||
requestID = uuid.New().String()
|
||||
}
|
||||
// Set request ID in header
|
||||
c.Header("X-Request-ID", requestID)
|
||||
|
||||
// Set request ID in context
|
||||
c.Set(types.RequestIDContextKey.String(), requestID)
|
||||
|
||||
// Set logger in context
|
||||
requestLogger := logger.GetLogger(c)
|
||||
requestLogger = requestLogger.WithField("request_id", requestID)
|
||||
c.Set(types.LoggerContextKey.String(), requestLogger)
|
||||
|
||||
// Set request ID in the global context for logging
|
||||
c.Request = c.Request.WithContext(
|
||||
context.WithValue(
|
||||
context.WithValue(c.Request.Context(), types.RequestIDContextKey, requestID),
|
||||
types.LoggerContextKey, requestLogger,
|
||||
),
|
||||
)
|
||||
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
// Logger middleware logs request details with request ID
|
||||
func Logger() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
start := time.Now()
|
||||
path := c.Request.URL.Path
|
||||
raw := c.Request.URL.RawQuery
|
||||
|
||||
// Process request
|
||||
c.Next()
|
||||
|
||||
// Get request ID from context
|
||||
requestID, exists := c.Get(types.RequestIDContextKey.String())
|
||||
if !exists {
|
||||
requestID = "unknown"
|
||||
}
|
||||
|
||||
// Calculate latency
|
||||
latency := time.Since(start)
|
||||
|
||||
// Get client IP and status code
|
||||
clientIP := c.ClientIP()
|
||||
statusCode := c.Writer.Status()
|
||||
method := c.Request.Method
|
||||
|
||||
if raw != "" {
|
||||
path = path + "?" + raw
|
||||
}
|
||||
|
||||
// Log with request ID
|
||||
logger.GetLogger(c).Infof("[%s] %d | %3d | %13v | %15s | %s %s",
|
||||
requestID,
|
||||
statusCode,
|
||||
c.Writer.Size(),
|
||||
latency,
|
||||
clientIP,
|
||||
method,
|
||||
path,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"runtime/debug"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// Recovery is a middleware that recovers from panics
|
||||
func Recovery() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
defer func() {
|
||||
if err := recover(); err != nil {
|
||||
// Get request ID
|
||||
requestID, _ := c.Get("RequestID")
|
||||
|
||||
// Print stacktrace
|
||||
stacktrace := debug.Stack()
|
||||
// Log error
|
||||
log.Printf("[PANIC] %s | %v | %s", requestID, err, stacktrace)
|
||||
|
||||
// 返回500错误
|
||||
c.AbortWithStatusJSON(500, gin.H{
|
||||
"error": "Internal Server Error",
|
||||
"message": fmt.Sprintf("%v", err),
|
||||
})
|
||||
}
|
||||
}()
|
||||
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"io"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/codes"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/tracing"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
)
|
||||
|
||||
// Custom ResponseWriter to capture response content
|
||||
type responseBodyWriter struct {
|
||||
gin.ResponseWriter
|
||||
body *bytes.Buffer
|
||||
}
|
||||
|
||||
// Override Write method to write response content to buffer and original writer
|
||||
func (r responseBodyWriter) Write(b []byte) (int, error) {
|
||||
r.body.Write(b)
|
||||
return r.ResponseWriter.Write(b)
|
||||
}
|
||||
|
||||
// TracingMiddleware provides a Gin middleware that creates a trace span for each request
|
||||
func TracingMiddleware() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
// Extract trace context from request headers
|
||||
propagator := tracing.GetTracer()
|
||||
if propagator == nil {
|
||||
c.Next()
|
||||
return
|
||||
}
|
||||
|
||||
// Get request ID as Span ID
|
||||
requestID := c.GetString(string(types.RequestIDContextKey))
|
||||
if requestID == "" {
|
||||
requestID = c.GetHeader("X-Request-ID")
|
||||
}
|
||||
|
||||
// Create new span
|
||||
spanName := fmt.Sprintf("%s %s", c.Request.Method, c.FullPath())
|
||||
ctx, span := tracing.ContextWithSpan(c.Request.Context(), spanName)
|
||||
defer span.End()
|
||||
|
||||
// Set basic span attributes
|
||||
span.SetAttributes(
|
||||
attribute.String("http.method", c.Request.Method),
|
||||
attribute.String("http.url", c.Request.URL.String()),
|
||||
attribute.String("http.path", c.FullPath()),
|
||||
)
|
||||
|
||||
// Record request headers (optional, or selectively record important headers)
|
||||
for key, values := range c.Request.Header {
|
||||
// Skip sensitive or unnecessary headers
|
||||
if strings.ToLower(key) == "authorization" || strings.ToLower(key) == "cookie" {
|
||||
continue
|
||||
}
|
||||
span.SetAttributes(attribute.String("http.request.header."+key, strings.Join(values, ";")))
|
||||
}
|
||||
|
||||
// Record request body (for POST/PUT/PATCH requests)
|
||||
if c.Request.Method == "POST" || c.Request.Method == "PUT" || c.Request.Method == "PATCH" {
|
||||
if c.Request.Body != nil {
|
||||
bodyBytes, _ := io.ReadAll(c.Request.Body)
|
||||
span.SetAttributes(attribute.String("http.request.body", string(bodyBytes)))
|
||||
// Reset request body because ReadAll consumes the Reader content
|
||||
c.Request.Body = io.NopCloser(bytes.NewBuffer(bodyBytes))
|
||||
}
|
||||
}
|
||||
|
||||
// Record query parameters
|
||||
if len(c.Request.URL.RawQuery) > 0 {
|
||||
span.SetAttributes(attribute.String("http.request.query", c.Request.URL.RawQuery))
|
||||
}
|
||||
|
||||
// Set request context with span context
|
||||
c.Request = c.Request.WithContext(ctx)
|
||||
|
||||
// Store tracing context in Gin context
|
||||
c.Set("trace.span", span)
|
||||
c.Set("trace.ctx", ctx)
|
||||
|
||||
// Create response body capturer
|
||||
responseBody := &bytes.Buffer{}
|
||||
responseWriter := &responseBodyWriter{
|
||||
ResponseWriter: c.Writer,
|
||||
body: responseBody,
|
||||
}
|
||||
c.Writer = responseWriter
|
||||
|
||||
// Process request
|
||||
c.Next()
|
||||
|
||||
// Set response status code
|
||||
statusCode := c.Writer.Status()
|
||||
span.SetAttributes(attribute.Int("http.status_code", statusCode))
|
||||
|
||||
// Record response body
|
||||
responseContent := responseBody.String()
|
||||
if len(responseContent) > 0 {
|
||||
span.SetAttributes(attribute.String("http.response.body", responseContent))
|
||||
}
|
||||
|
||||
// Record response headers (optional, or selectively record important headers)
|
||||
for key, values := range c.Writer.Header() {
|
||||
span.SetAttributes(attribute.String("http.response.header."+key, strings.Join(values, ";")))
|
||||
}
|
||||
|
||||
// Mark as error if status code >= 400
|
||||
if statusCode >= 400 {
|
||||
span.SetStatus(codes.Error, fmt.Sprintf("HTTP %d", statusCode))
|
||||
if err := c.Errors.Last(); err != nil {
|
||||
span.RecordError(err.Err)
|
||||
}
|
||||
} else {
|
||||
span.SetStatus(codes.Ok, "")
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user