Refactor error handling and variable declarations in browser and logging modules

- Simplified variable initialization in `browser.go` for readability.
- Updated error handling in `request_logger.go` with better resource cleanup using deferred anonymous functions.

Refactor API handlers to use `GetContextWithCancel` for streamlined context creation and response handling

- Replaced redundant `context.WithCancel` and `context.WithValue` logic with the new `GetContextWithCancel` utility in all handlers.
- Centralized API response storage in the given context during cancellation.
- Updated associated cancellation calls for consistency and improved resource management.

- Replaced `apiResponseData` with `AddAPIResponseData` for centralized response recording.
- Simplified cancellation logic by switching to a boolean-based `cliCancel` method.
- Removed unused `apiResponseData` slices across handlers to reduce memory usage.
- Updated `handlers.go` to support unified response data storage per request context.
This commit is contained in:
Luis Pater
2025-08-17 18:34:15 +08:00
parent 6bbdf67f96
commit c5cc238308
7 changed files with 115 additions and 118 deletions

View File

@@ -108,8 +108,7 @@ func (h *ClaudeCodeAPIHandlers) handleGeminiStreamingResponse(c *gin.Context, ra
// Create a cancellable context for the backend client request
// This allows proper cleanup and cancellation of ongoing requests
backgroundCtx, cliCancel := context.WithCancel(context.Background())
cliCtx := context.WithValue(backgroundCtx, "gin", c)
cliCtx, cliCancel := h.GetContextWithCancel(c, context.Background())
var cliClient client.Client
cliClient = client.NewGeminiClient(nil, nil, nil)
@@ -159,7 +158,6 @@ outLoop:
responseType := 0
responseIndex := 0
apiResponseData := make([]byte, 0)
// Main streaming loop - handles multiple concurrent events using Go channels
// This select statement manages four different types of events simultaneously
for {
@@ -169,7 +167,6 @@ outLoop:
case <-c.Request.Context().Done():
if c.Request.Context().Err().Error() == "context canceled" {
log.Debugf("GeminiClient disconnected: %v", c.Request.Context().Err())
c.Set("API_RESPONSE", apiResponseData)
cliCancel() // Cancel the backend request to prevent resource leaks
return
}
@@ -186,12 +183,11 @@ outLoop:
_, _ = c.Writer.Write([]byte("\n\n\n"))
flusher.Flush()
c.Set("API_RESPONSE", apiResponseData)
cliCancel()
return
}
apiResponseData = append(apiResponseData, chunk...)
h.AddAPIResponseData(c, chunk)
// Convert the backend response to Claude-compatible format
// This translation layer ensures API compatibility
claudeFormat := translatorClaudeCodeToGeminiCli.ConvertCliResponseToClaudeCode(chunk, isGlAPIKey, hasFirstResponse, &responseType, &responseIndex)
@@ -214,8 +210,7 @@ outLoop:
c.Status(errInfo.StatusCode)
_, _ = fmt.Fprint(c.Writer, errInfo.Error.Error())
flusher.Flush()
c.Set("API_RESPONSE", []byte(errInfo.Error.Error()))
cliCancel()
cliCancel(errInfo.Error)
}
return
}
@@ -280,8 +275,7 @@ func (h *ClaudeCodeAPIHandlers) handleCodexStreamingResponse(c *gin.Context, raw
// return
// Create a cancellable context for the backend client request
// This allows proper cleanup and cancellation of ongoing requests
backgroundCtx, cliCancel := context.WithCancel(context.Background())
cliCtx := context.WithValue(backgroundCtx, "gin", c)
cliCtx, cliCancel := h.GetContextWithCancel(c, context.Background())
var cliClient client.Client
defer func() {
@@ -316,7 +310,6 @@ outLoop:
hasFirstResponse := false
hasToolCall := false
apiResponseData := make([]byte, 0)
// Main streaming loop - handles multiple concurrent events using Go channels
// This select statement manages four different types of events simultaneously
for {
@@ -326,7 +319,6 @@ outLoop:
case <-c.Request.Context().Done():
if c.Request.Context().Err().Error() == "context canceled" {
log.Debugf("CodexClient disconnected: %v", c.Request.Context().Err())
c.Set("API_RESPONSE", apiResponseData)
cliCancel() // Cancel the backend request to prevent resource leaks
return
}
@@ -336,11 +328,12 @@ outLoop:
case chunk, okStream := <-respChan:
if !okStream {
flusher.Flush()
c.Set("API_RESPONSE", apiResponseData)
cliCancel()
return
}
apiResponseData = append(apiResponseData, chunk...)
h.AddAPIResponseData(c, chunk)
// Convert the backend response to Claude-compatible format
// This translation layer ensures API compatibility
if bytes.HasPrefix(chunk, []byte("data: ")) {
@@ -371,9 +364,8 @@ outLoop:
// Forward other errors directly to the client
c.Status(errInfo.StatusCode)
_, _ = fmt.Fprint(c.Writer, errInfo.Error.Error())
c.Set("API_RESPONSE", []byte(errInfo.Error.Error()))
flusher.Flush()
cliCancel()
cliCancel(errInfo.Error)
}
return
}