Skip to content

feat: 自定义请求头 - #1447

Closed
youtiaoguagua wants to merge 0 commit into
QuantumNous:alphafrom
youtiaoguagua:alpha
Closed

feat: 自定义请求头#1447
youtiaoguagua wants to merge 0 commit into
QuantumNous:alphafrom
youtiaoguagua:alpha

Conversation

@youtiaoguagua

@youtiaoguagua youtiaoguagua commented Jul 26, 2025

Copy link
Copy Markdown

增加覆写请求头,增加对edgeone ai网关的支持

Fixes #1313

Summary by CodeRabbit

  • New Features

    • Added support for custom request header overrides on channels, allowing users to specify header values via a new JSON input in the channel editing modal.
    • Introduced special handling for Tencent EdgeOne gateway requests, enabling API key injection as a query parameter when applicable.
  • User Interface

    • Added a "Request Header override" JSON textarea in the channel advanced settings, with a template fill option for easier configuration.

@coderabbitai

coderabbitai Bot commented Jul 26, 2025

Copy link
Copy Markdown
Contributor

Walkthrough

A new feature was introduced allowing custom HTTP headers to be specified and overridden on a per-channel basis. This involved adding a HeaderOverride field to the channel model, exposing it in the UI, passing it through middleware and context, and applying these header overrides in API requests and URL construction, with special handling for certain gateway scenarios.

Changes

File(s) Change Summary
constant/context_key.go Added new context key constant for channel header override.
model/channel.go Added HeaderOverride field to Channel struct and a GetHeaderOverride() method.
middleware/distributor.go Set new header override context key in channel context setup.
relay/common/relay_info.go Added HeaderOverride field to RelayInfo and initialized it from context in GenRelayInfo().
relay/channel/api_request.go Modified SetupApiRequestHeader to apply header overrides from RelayInfo.HeaderOverride.
relay/channel/gemini/adaptor.go Modified GetRequestURL to append API key as query param if OE-Key header override is present.
web/src/components/table/channels/modals/EditChannelModal.jsx Added a new textarea input for header overrides in the channel edit modal UI.
web/src/i18n/locales/en.json Added English localization entries for header override label and description.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant UI (EditChannelModal)
    participant Backend (API)
    participant DB
    participant Middleware
    participant Relay
    participant Upstream API

    User->>UI (EditChannelModal): Enters header override JSON
    UI (EditChannelModal)->>Backend (API): Submits channel config with header_override
    Backend (API)->>DB: Stores header_override in Channel record
    User->>Backend (API): Initiates request via selected channel
    Backend (API)->>Middleware: Sets up context, includes header_override
    Middleware->>Relay: Passes RelayInfo with header_override
    Relay->>Upstream API: Applies header overrides to request headers
    Upstream API-->>Relay: Processes request
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~15 minutes

Poem

A rabbit hops with headers new,
Custom keys in every queue.
Through forms and fields, the JSON flows,
With "OE-Key" the channel knows.
Now every hop, a header ride—
Override with bunny pride!
🐇✨

Note

⚡️ Unit Test Generation is now available in beta!

Learn more here, or try it out under "Finishing Touches" below.


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 626768a and caaf323.

📒 Files selected for processing (2)
  • web/src/components/table/channels/modals/EditChannelModal.jsx (1 hunks)
  • web/src/i18n/locales/en.json (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • web/src/i18n/locales/en.json
🚧 Files skipped from review as they are similar to previous changes (1)
  • web/src/components/table/channels/modals/EditChannelModal.jsx
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (2)
relay/channel/api_request.go (1)

36-47: Consider improving error handling for header value conversion.

The header override implementation is functionally correct, but the type conversion silently ignores errors. Consider logging conversion failures to help with debugging invalid header configurations.

 if len(info.HeaderOverride) > 0 {
 	for k, v := range info.HeaderOverride {
-		value, _ := common2.Any2Type[string](v)
+		value, err := common2.Any2Type[string](v)
+		if err != nil && common2.DebugEnabled {
+			println("Failed to convert header override value for key", k, ":", err.Error())
+			continue
+		}
 		req.Set(k, value)
 	}
 }
relay/channel/gemini/adaptor.go (1)

109-122: Solid implementation with proper error handling.

The EdgeOne gateway handling is well-implemented with appropriate error handling and URL manipulation. The logic correctly:

  • Checks for the presence of the "OE-Key" header override
  • Handles URL parsing errors gracefully
  • Properly manipulates query parameters

Consider simplifying the conditional check:

-	if _, ok := info.HeaderOverride["OE-Key"]; len(info.HeaderOverride) > 0 && ok {
+	if _, ok := info.HeaderOverride["OE-Key"]; ok {

The length check is redundant since we're already verifying key existence with ok.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between a8a42cb and 626768a.

📒 Files selected for processing (7)
  • constant/context_key.go (1 hunks)
  • middleware/distributor.go (1 hunks)
  • model/channel.go (2 hunks)
  • relay/channel/api_request.go (1 hunks)
  • relay/channel/gemini/adaptor.go (2 hunks)
  • relay/common/relay_info.go (3 hunks)
  • web/src/components/table/channels/modals/EditChannelModal.jsx (1 hunks)
🧰 Additional context used
🧠 Learnings (2)
relay/common/relay_info.go (1)

Learnt from: 9Ninety
PR: #1273
File: relay/channel/gemini/relay-gemini.go:97-116
Timestamp: 2025-06-21T03:37:41.726Z
Learning: In relay/channel/gemini/relay-gemini.go, the thinking budget calculation logic (including the MaxOutputTokens multiplication) was introduced in PR #1247. PR #1273 focused specifically on decoupling the thoughts summary feature from thinking budget settings and did not modify the existing thinking budget behavior.

middleware/distributor.go (2)

Learnt from: feitianbubu
PR: #1228
File: router/main.go:28-36
Timestamp: 2025-06-15T12:38:11.806Z
Learning: gin.Context implements context.Context interface since Gin v1.8.0, providing the methods Deadline(), Done(), Err(), and Value(). When using Gin v1.8.0 or later, gin.Context can be passed directly to functions expecting context.Context without needing to extract c.Request.Context().

Learnt from: feitianbubu
PR: #1228
File: router/main.go:28-36
Timestamp: 2025-06-15T12:38:11.806Z
Learning: gin.Context implements context.Context interface since Gin v1.8.0, providing the methods Deadline(), Done(), Err(), and Value(). When using Gin v1.8.0 or later, gin.Context can be passed directly to functions expecting context.Context without needing to extract c.Request.Context().

🔇 Additional comments (9)
constant/context_key.go (1)

27-27: LGTM! Well-named constant addition.

The new context key follows the established naming convention and is appropriately placed among other channel-related constants.

middleware/distributor.go (1)

258-258: LGTM! Consistent with existing context setup pattern.

The header override context setup follows the same pattern as other channel-related context keys like ParamOverride and ChannelSetting.

model/channel.go (2)

47-47: LGTM! Consistent field addition.

The HeaderOverride field follows the same pattern as other JSON configuration fields like ParamOverride and StatusCodeMapping.


823-832: LGTM! Well-implemented getter method.

The GetHeaderOverride() method follows the established pattern used by GetParamOverride() and includes proper error handling with logging.

relay/common/relay_info.go (2)

102-102: LGTM! Consistent field addition to RelayInfo struct.

The HeaderOverride field follows the same pattern and type as the existing ParamOverride field.


220-220: LGTM! Proper initialization following established pattern.

The header override initialization follows the same pattern as ParamOverride and correctly extracts the value from the Gin context.

Also applies to: 259-259

relay/channel/gemini/adaptor.go (2)

9-9: LGTM! Import addition is appropriate.

The net/url import is correctly added to support the new URL parsing functionality for EdgeOne gateway handling.


108-108: Good refactoring to support conditional URL modification.

The URL construction is extracted into a variable to enable conditional processing while maintaining the existing functionality.

web/src/components/table/channels/modals/EditChannelModal.jsx (1)

1553-1571: Well-implemented form field following established patterns.

The header override field implementation is excellent:

  • Consistent with existing form field patterns in the component
  • Proper internationalization support
  • Good UX with placeholder example, template filler, and clear functionality
  • Appropriate placement in the Advanced Settings section
  • Template value aligns with backend expectations (OE-Key for EdgeOne gateway)

The implementation maintains consistency with similar fields like param_override and status_code_mapping.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant