refactor(logging): replace gin-specific context handling with generic context-based request metadata utilities

- Introduced reusable utilities in `requestmeta` to manage endpoint and response status in request contexts.
- Refactored plugins and handlers to use context-based metadata, removing direct dependency on `gin`.
- Updated tests to validate new context utilities and replaced `gin`-based context handling.

Fixed: #3166
This commit is contained in:
Luis Pater
2026-04-30 23:36:07 +08:00
parent 8b286e8fb3
commit 4035abc0cd
5 changed files with 174 additions and 68 deletions
+25 -1
View File
@@ -375,11 +375,32 @@ func (h *BaseAPIHandler) GetContextWithCancel(handler interfaces.APIHandler, c *
if requestCtx != nil && logging.GetRequestID(parentCtx) == "" {
if requestID := logging.GetRequestID(requestCtx); requestID != "" {
parentCtx = logging.WithRequestID(parentCtx, requestID)
} else if requestID := logging.GetGinRequestID(c); requestID != "" {
} else if requestID = logging.GetGinRequestID(c); requestID != "" {
parentCtx = logging.WithRequestID(parentCtx, requestID)
}
}
newCtx, cancel := context.WithCancel(parentCtx)
endpoint := ""
if c != nil && c.Request != nil {
path := strings.TrimSpace(c.FullPath())
if path == "" && c.Request.URL != nil {
path = strings.TrimSpace(c.Request.URL.Path)
}
if path != "" {
method := strings.TrimSpace(c.Request.Method)
if method != "" {
endpoint = method + " " + path
} else {
endpoint = path
}
}
}
if endpoint != "" {
newCtx = logging.WithEndpoint(newCtx, endpoint)
}
newCtx = logging.WithResponseStatusHolder(newCtx)
cancelCtx := newCtx
if requestCtx != nil && requestCtx != parentCtx {
go func() {
@@ -393,6 +414,9 @@ func (h *BaseAPIHandler) GetContextWithCancel(handler interfaces.APIHandler, c *
newCtx = context.WithValue(newCtx, "gin", c)
newCtx = context.WithValue(newCtx, "handler", handler)
return newCtx, func(params ...interface{}) {
if c != nil {
logging.SetResponseStatus(cancelCtx, c.Writer.Status())
}
if h.Cfg.RequestLog && len(params) == 1 {
if existing, exists := c.Get("API_RESPONSE"); exists {
if existingBytes, ok := existing.([]byte); ok && len(bytes.TrimSpace(existingBytes)) > 0 {