refactor(config): migrate to SDKConfig and streamline proxy handling

- Replaced `config.Config` with `config.SDKConfig` across components for simpler configuration management.
- Updated proxy setup functions and handlers to align with `SDKConfig` improvements.
- Reorganized handler imports to match new SDK structure.
This commit is contained in:
Luis Pater
2025-09-27 04:50:23 +08:00
parent 40255b128e
commit 57c9ba49f4
17 changed files with 61 additions and 51 deletions

View File

@@ -449,7 +449,7 @@ func (h *Handler) RequestAnthropicToken(c *gin.Context) {
} }
bodyJSON, _ := json.Marshal(bodyMap) bodyJSON, _ := json.Marshal(bodyMap)
httpClient := util.SetProxy(h.cfg, &http.Client{}) httpClient := util.SetProxy(&h.cfg.SDKConfig, &http.Client{})
req, _ := http.NewRequestWithContext(ctx, "POST", "https://console.anthropic.com/v1/oauth/token", strings.NewReader(string(bodyJSON))) req, _ := http.NewRequestWithContext(ctx, "POST", "https://console.anthropic.com/v1/oauth/token", strings.NewReader(string(bodyJSON)))
req.Header.Set("Content-Type", "application/json") req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept", "application/json") req.Header.Set("Accept", "application/json")
@@ -818,7 +818,7 @@ func (h *Handler) RequestCodexToken(c *gin.Context) {
"redirect_uri": {"http://localhost:1455/auth/callback"}, "redirect_uri": {"http://localhost:1455/auth/callback"},
"code_verifier": {pkceCodes.CodeVerifier}, "code_verifier": {pkceCodes.CodeVerifier},
} }
httpClient := util.SetProxy(h.cfg, &http.Client{}) httpClient := util.SetProxy(&h.cfg.SDKConfig, &http.Client{})
req, _ := http.NewRequestWithContext(ctx, "POST", "https://auth.openai.com/oauth/token", strings.NewReader(form.Encode())) req, _ := http.NewRequestWithContext(ctx, "POST", "https://auth.openai.com/oauth/token", strings.NewReader(form.Encode()))
req.Header.Set("Content-Type", "application/x-www-form-urlencoded") req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.Header.Set("Accept", "application/json") req.Header.Set("Accept", "application/json")

View File

@@ -16,17 +16,17 @@ import (
"time" "time"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"github.com/router-for-me/CLIProxyAPI/v6/internal/api/handlers"
"github.com/router-for-me/CLIProxyAPI/v6/internal/api/handlers/claude"
"github.com/router-for-me/CLIProxyAPI/v6/internal/api/handlers/gemini"
managementHandlers "github.com/router-for-me/CLIProxyAPI/v6/internal/api/handlers/management" managementHandlers "github.com/router-for-me/CLIProxyAPI/v6/internal/api/handlers/management"
"github.com/router-for-me/CLIProxyAPI/v6/internal/api/handlers/openai"
"github.com/router-for-me/CLIProxyAPI/v6/internal/api/middleware" "github.com/router-for-me/CLIProxyAPI/v6/internal/api/middleware"
"github.com/router-for-me/CLIProxyAPI/v6/internal/config" "github.com/router-for-me/CLIProxyAPI/v6/internal/config"
"github.com/router-for-me/CLIProxyAPI/v6/internal/logging" "github.com/router-for-me/CLIProxyAPI/v6/internal/logging"
"github.com/router-for-me/CLIProxyAPI/v6/internal/usage" "github.com/router-for-me/CLIProxyAPI/v6/internal/usage"
"github.com/router-for-me/CLIProxyAPI/v6/internal/util" "github.com/router-for-me/CLIProxyAPI/v6/internal/util"
sdkaccess "github.com/router-for-me/CLIProxyAPI/v6/sdk/access" sdkaccess "github.com/router-for-me/CLIProxyAPI/v6/sdk/access"
"github.com/router-for-me/CLIProxyAPI/v6/sdk/api/handlers"
"github.com/router-for-me/CLIProxyAPI/v6/sdk/api/handlers/claude"
gemini2 "github.com/router-for-me/CLIProxyAPI/v6/sdk/api/handlers/gemini"
openai2 "github.com/router-for-me/CLIProxyAPI/v6/sdk/api/handlers/openai"
"github.com/router-for-me/CLIProxyAPI/v6/sdk/cliproxy/auth" "github.com/router-for-me/CLIProxyAPI/v6/sdk/cliproxy/auth"
log "github.com/sirupsen/logrus" log "github.com/sirupsen/logrus"
) )
@@ -187,7 +187,7 @@ func NewServer(cfg *config.Config, authManager *auth.Manager, accessManager *sdk
// Create server instance // Create server instance
s := &Server{ s := &Server{
engine: engine, engine: engine,
handlers: handlers.NewBaseAPIHandlers(cfg, authManager), handlers: handlers.NewBaseAPIHandlers(&cfg.SDKConfig, authManager),
cfg: cfg, cfg: cfg,
accessManager: accessManager, accessManager: accessManager,
requestLogger: requestLogger, requestLogger: requestLogger,
@@ -224,11 +224,11 @@ func NewServer(cfg *config.Config, authManager *auth.Manager, accessManager *sdk
// setupRoutes configures the API routes for the server. // setupRoutes configures the API routes for the server.
// It defines the endpoints and associates them with their respective handlers. // It defines the endpoints and associates them with their respective handlers.
func (s *Server) setupRoutes() { func (s *Server) setupRoutes() {
openaiHandlers := openai.NewOpenAIAPIHandler(s.handlers) openaiHandlers := openai2.NewOpenAIAPIHandler(s.handlers)
geminiHandlers := gemini.NewGeminiAPIHandler(s.handlers) geminiHandlers := gemini2.NewGeminiAPIHandler(s.handlers)
geminiCLIHandlers := gemini.NewGeminiCLIAPIHandler(s.handlers) geminiCLIHandlers := gemini2.NewGeminiCLIAPIHandler(s.handlers)
claudeCodeHandlers := claude.NewClaudeCodeAPIHandler(s.handlers) claudeCodeHandlers := claude.NewClaudeCodeAPIHandler(s.handlers)
openaiResponsesHandlers := openai.NewOpenAIResponsesAPIHandler(s.handlers) openaiResponsesHandlers := openai2.NewOpenAIResponsesAPIHandler(s.handlers)
// OpenAI compatible API routes // OpenAI compatible API routes
v1 := s.engine.Group("/v1") v1 := s.engine.Group("/v1")
@@ -469,7 +469,7 @@ func (s *Server) watchKeepAlive() {
// that routes to different handlers based on the User-Agent header. // that routes to different handlers based on the User-Agent header.
// If User-Agent starts with "claude-cli", it routes to Claude handler, // If User-Agent starts with "claude-cli", it routes to Claude handler,
// otherwise it routes to OpenAI handler. // otherwise it routes to OpenAI handler.
func (s *Server) unifiedModelsHandler(openaiHandler *openai.OpenAIAPIHandler, claudeHandler *claude.ClaudeCodeAPIHandler) gin.HandlerFunc { func (s *Server) unifiedModelsHandler(openaiHandler *openai2.OpenAIAPIHandler, claudeHandler *claude.ClaudeCodeAPIHandler) gin.HandlerFunc {
return func(c *gin.Context) { return func(c *gin.Context) {
userAgent := c.GetHeader("User-Agent") userAgent := c.GetHeader("User-Agent")
@@ -622,7 +622,7 @@ func (s *Server) UpdateClients(cfg *config.Config) {
s.applyAccessConfig(oldCfg, cfg) s.applyAccessConfig(oldCfg, cfg)
s.cfg = cfg s.cfg = cfg
s.handlers.UpdateClients(cfg) s.handlers.UpdateClients(&cfg.SDKConfig)
if s.mgmt != nil { if s.mgmt != nil {
s.mgmt.SetConfig(cfg) s.mgmt.SetConfig(cfg)
s.mgmt.SetAuthManager(s.handlers.AuthManager) s.mgmt.SetAuthManager(s.handlers.AuthManager)

View File

@@ -59,7 +59,7 @@ type ClaudeAuth struct {
// - *ClaudeAuth: A new Claude authentication service instance // - *ClaudeAuth: A new Claude authentication service instance
func NewClaudeAuth(cfg *config.Config) *ClaudeAuth { func NewClaudeAuth(cfg *config.Config) *ClaudeAuth {
return &ClaudeAuth{ return &ClaudeAuth{
httpClient: util.SetProxy(cfg, &http.Client{}), httpClient: util.SetProxy(&cfg.SDKConfig, &http.Client{}),
} }
} }

View File

@@ -37,7 +37,7 @@ type CodexAuth struct {
// It initializes an HTTP client with proxy settings from the provided configuration. // It initializes an HTTP client with proxy settings from the provided configuration.
func NewCodexAuth(cfg *config.Config) *CodexAuth { func NewCodexAuth(cfg *config.Config) *CodexAuth {
return &CodexAuth{ return &CodexAuth{
httpClient: util.SetProxy(cfg, &http.Client{}), httpClient: util.SetProxy(&cfg.SDKConfig, &http.Client{}),
} }
} }

View File

@@ -85,7 +85,7 @@ type QwenAuth struct {
// NewQwenAuth creates a new QwenAuth instance with a proxy-configured HTTP client. // NewQwenAuth creates a new QwenAuth instance with a proxy-configured HTTP client.
func NewQwenAuth(cfg *config.Config) *QwenAuth { func NewQwenAuth(cfg *config.Config) *QwenAuth {
return &QwenAuth{ return &QwenAuth{
httpClient: util.SetProxy(cfg, &http.Client{}), httpClient: util.SetProxy(&cfg.SDKConfig, &http.Client{}),
} }
} }

View File

@@ -75,7 +75,7 @@ func DoGeminiWebAuth(cfg *config.Config) {
// Build HTTP client with proxy settings respected. // Build HTTP client with proxy settings respected.
httpClient := &http.Client{Timeout: 15 * time.Second} httpClient := &http.Client{Timeout: 15 * time.Second}
httpClient = util.SetProxy(cfg, httpClient) httpClient = util.SetProxy(&cfg.SDKConfig, httpClient)
// Request ListAccounts to extract email as label (use POST per upstream behavior). // Request ListAccounts to extract email as label (use POST per upstream behavior).
req, err := http.NewRequest(http.MethodPost, "https://accounts.google.com/ListAccounts", nil) req, err := http.NewRequest(http.MethodPost, "https://accounts.google.com/ListAccounts", nil)
@@ -88,8 +88,8 @@ func DoGeminiWebAuth(cfg *config.Config) {
req.Header.Set("Origin", "https://accounts.google.com") req.Header.Set("Origin", "https://accounts.google.com")
req.Header.Set("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8") req.Header.Set("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8")
resp, err := httpClient.Do(req) resp, errDo := httpClient.Do(req)
if err != nil { if errDo != nil {
fmt.Println("!! Request to ListAccounts failed:", err) fmt.Println("!! Request to ListAccounts failed:", err)
} else { } else {
defer func() { _ = resp.Body.Close() }() defer func() { _ = resp.Body.Close() }()

View File

@@ -8,12 +8,14 @@ import (
"fmt" "fmt"
"os" "os"
"github.com/router-for-me/CLIProxyAPI/v6/sdk/config"
"golang.org/x/crypto/bcrypt" "golang.org/x/crypto/bcrypt"
"gopkg.in/yaml.v3" "gopkg.in/yaml.v3"
) )
// Config represents the application's configuration, loaded from a YAML file. // Config represents the application's configuration, loaded from a YAML file.
type Config struct { type Config struct {
config.SDKConfig
// Port is the network port on which the API server will listen. // Port is the network port on which the API server will listen.
Port int `yaml:"port" json:"-"` Port int `yaml:"port" json:"-"`
@@ -29,9 +31,6 @@ type Config struct {
// UsageStatisticsEnabled toggles in-memory usage aggregation; when false, usage data is discarded. // UsageStatisticsEnabled toggles in-memory usage aggregation; when false, usage data is discarded.
UsageStatisticsEnabled bool `yaml:"usage-statistics-enabled" json:"usage-statistics-enabled"` UsageStatisticsEnabled bool `yaml:"usage-statistics-enabled" json:"usage-statistics-enabled"`
// ProxyURL is the URL of an optional proxy server to use for outbound requests.
ProxyURL string `yaml:"proxy-url" json:"proxy-url"`
// APIKeys is a list of keys for authenticating clients to this proxy server. // APIKeys is a list of keys for authenticating clients to this proxy server.
APIKeys []string `yaml:"api-keys" json:"api-keys"` APIKeys []string `yaml:"api-keys" json:"api-keys"`
@@ -44,9 +43,6 @@ type Config struct {
// GlAPIKey is the API key for the generative language API. // GlAPIKey is the API key for the generative language API.
GlAPIKey []string `yaml:"generative-language-api-key" json:"generative-language-api-key"` GlAPIKey []string `yaml:"generative-language-api-key" json:"generative-language-api-key"`
// RequestLog enables or disables detailed request logging functionality.
RequestLog bool `yaml:"request-log" json:"request-log"`
// RequestRetry defines the retry times when the request failed. // RequestRetry defines the retry times when the request failed.
RequestRetry int `yaml:"request-retry" json:"request-retry"` RequestRetry int `yaml:"request-retry" json:"request-retry"`
@@ -206,23 +202,23 @@ func LoadConfig(configFile string) (*Config, error) {
} }
// Unmarshal the YAML data into the Config struct. // Unmarshal the YAML data into the Config struct.
var config Config var cfg Config
// Set defaults before unmarshal so that absent keys keep defaults. // Set defaults before unmarshal so that absent keys keep defaults.
config.LoggingToFile = true cfg.LoggingToFile = true
config.UsageStatisticsEnabled = true cfg.UsageStatisticsEnabled = true
config.GeminiWeb.Context = true cfg.GeminiWeb.Context = true
if err = yaml.Unmarshal(data, &config); err != nil { if err = yaml.Unmarshal(data, &cfg); err != nil {
return nil, fmt.Errorf("failed to parse config file: %w", err) return nil, fmt.Errorf("failed to parse config file: %w", err)
} }
// Hash remote management key if plaintext is detected (nested) // Hash remote management key if plaintext is detected (nested)
// We consider a value to be already hashed if it looks like a bcrypt hash ($2a$, $2b$, or $2y$ prefix). // We consider a value to be already hashed if it looks like a bcrypt hash ($2a$, $2b$, or $2y$ prefix).
if config.RemoteManagement.SecretKey != "" && !looksLikeBcrypt(config.RemoteManagement.SecretKey) { if cfg.RemoteManagement.SecretKey != "" && !looksLikeBcrypt(cfg.RemoteManagement.SecretKey) {
hashed, errHash := hashSecret(config.RemoteManagement.SecretKey) hashed, errHash := hashSecret(cfg.RemoteManagement.SecretKey)
if errHash != nil { if errHash != nil {
return nil, fmt.Errorf("failed to hash remote management key: %w", errHash) return nil, fmt.Errorf("failed to hash remote management key: %w", errHash)
} }
config.RemoteManagement.SecretKey = hashed cfg.RemoteManagement.SecretKey = hashed
// Persist the hashed value back to the config file to avoid re-hashing on next startup. // Persist the hashed value back to the config file to avoid re-hashing on next startup.
// Preserve YAML comments and ordering; update only the nested key. // Preserve YAML comments and ordering; update only the nested key.
@@ -230,10 +226,10 @@ func LoadConfig(configFile string) (*Config, error) {
} }
// Sync request authentication providers with inline API keys for backwards compatibility. // Sync request authentication providers with inline API keys for backwards compatibility.
syncInlineAccessProvider(&config) syncInlineAccessProvider(&cfg)
// Return the populated configuration struct. // Return the populated configuration struct.
return &config, nil return &cfg, nil
} }
// SyncInlineAPIKeys updates the inline API key provider and top-level APIKeys field. // SyncInlineAPIKeys updates the inline API key provider and top-level APIKeys field.

View File

@@ -320,7 +320,7 @@ func (e *GeminiExecutor) Refresh(ctx context.Context, auth *cliproxyauth.Auth) (
conf := &oauth2.Config{ClientID: clientID, ClientSecret: clientSecret, Endpoint: endpoint} conf := &oauth2.Config{ClientID: clientID, ClientSecret: clientSecret, Endpoint: endpoint}
// Ensure proxy-aware HTTP client for token refresh // Ensure proxy-aware HTTP client for token refresh
httpClient := util.SetProxy(e.cfg, &http.Client{}) httpClient := util.SetProxy(&e.cfg.SDKConfig, &http.Client{})
ctx = context.WithValue(ctx, oauth2.HTTPClient, httpClient) ctx = context.WithValue(ctx, oauth2.HTTPClient, httpClient)
// Build base token // Build base token

View File

@@ -26,7 +26,7 @@ import (
// //
// Returns: // Returns:
// - []string: All provider identifiers capable of serving the model, ordered by preference. // - []string: All provider identifiers capable of serving the model, ordered by preference.
func GetProviderName(modelName string, cfg *config.Config) []string { func GetProviderName(modelName string) []string {
if modelName == "" { if modelName == "" {
return nil return nil
} }

View File

@@ -9,7 +9,7 @@ import (
"net/http" "net/http"
"net/url" "net/url"
"github.com/router-for-me/CLIProxyAPI/v6/internal/config" "github.com/router-for-me/CLIProxyAPI/v6/sdk/config"
log "github.com/sirupsen/logrus" log "github.com/sirupsen/logrus"
"golang.org/x/net/proxy" "golang.org/x/net/proxy"
) )
@@ -17,7 +17,7 @@ import (
// SetProxy configures the provided HTTP client with proxy settings from the configuration. // SetProxy configures the provided HTTP client with proxy settings from the configuration.
// It supports SOCKS5, HTTP, and HTTPS proxies. The function modifies the client's transport // It supports SOCKS5, HTTP, and HTTPS proxies. The function modifies the client's transport
// to route requests through the configured proxy server. // to route requests through the configured proxy server.
func SetProxy(cfg *config.Config, httpClient *http.Client) *http.Client { func SetProxy(cfg *config.SDKConfig, httpClient *http.Client) *http.Client {
var transport *http.Transport var transport *http.Transport
// Attempt to parse the proxy URL from the configuration. // Attempt to parse the proxy URL from the configuration.
proxyURL, errParse := url.Parse(cfg.ProxyURL) proxyURL, errParse := url.Parse(cfg.ProxyURL)

View File

@@ -14,10 +14,10 @@ import (
"time" "time"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"github.com/router-for-me/CLIProxyAPI/v6/internal/api/handlers"
. "github.com/router-for-me/CLIProxyAPI/v6/internal/constant" . "github.com/router-for-me/CLIProxyAPI/v6/internal/constant"
"github.com/router-for-me/CLIProxyAPI/v6/internal/interfaces" "github.com/router-for-me/CLIProxyAPI/v6/internal/interfaces"
"github.com/router-for-me/CLIProxyAPI/v6/internal/registry" "github.com/router-for-me/CLIProxyAPI/v6/internal/registry"
"github.com/router-for-me/CLIProxyAPI/v6/sdk/api/handlers"
"github.com/tidwall/gjson" "github.com/tidwall/gjson"
) )

View File

@@ -14,10 +14,10 @@ import (
"time" "time"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"github.com/router-for-me/CLIProxyAPI/v6/internal/api/handlers"
. "github.com/router-for-me/CLIProxyAPI/v6/internal/constant" . "github.com/router-for-me/CLIProxyAPI/v6/internal/constant"
"github.com/router-for-me/CLIProxyAPI/v6/internal/interfaces" "github.com/router-for-me/CLIProxyAPI/v6/internal/interfaces"
"github.com/router-for-me/CLIProxyAPI/v6/internal/util" "github.com/router-for-me/CLIProxyAPI/v6/internal/util"
"github.com/router-for-me/CLIProxyAPI/v6/sdk/api/handlers"
log "github.com/sirupsen/logrus" log "github.com/sirupsen/logrus"
"github.com/tidwall/gjson" "github.com/tidwall/gjson"
) )

View File

@@ -13,10 +13,10 @@ import (
"time" "time"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"github.com/router-for-me/CLIProxyAPI/v6/internal/api/handlers"
. "github.com/router-for-me/CLIProxyAPI/v6/internal/constant" . "github.com/router-for-me/CLIProxyAPI/v6/internal/constant"
"github.com/router-for-me/CLIProxyAPI/v6/internal/interfaces" "github.com/router-for-me/CLIProxyAPI/v6/internal/interfaces"
"github.com/router-for-me/CLIProxyAPI/v6/internal/registry" "github.com/router-for-me/CLIProxyAPI/v6/internal/registry"
"github.com/router-for-me/CLIProxyAPI/v6/sdk/api/handlers"
) )
// GeminiAPIHandler contains the handlers for Gemini API endpoints. // GeminiAPIHandler contains the handlers for Gemini API endpoints.

View File

@@ -8,11 +8,11 @@ import (
"net/http" "net/http"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"github.com/router-for-me/CLIProxyAPI/v6/internal/config"
"github.com/router-for-me/CLIProxyAPI/v6/internal/interfaces" "github.com/router-for-me/CLIProxyAPI/v6/internal/interfaces"
"github.com/router-for-me/CLIProxyAPI/v6/internal/util" "github.com/router-for-me/CLIProxyAPI/v6/internal/util"
coreauth "github.com/router-for-me/CLIProxyAPI/v6/sdk/cliproxy/auth" coreauth "github.com/router-for-me/CLIProxyAPI/v6/sdk/cliproxy/auth"
coreexecutor "github.com/router-for-me/CLIProxyAPI/v6/sdk/cliproxy/executor" coreexecutor "github.com/router-for-me/CLIProxyAPI/v6/sdk/cliproxy/executor"
"github.com/router-for-me/CLIProxyAPI/v6/sdk/config"
sdktranslator "github.com/router-for-me/CLIProxyAPI/v6/sdk/translator" sdktranslator "github.com/router-for-me/CLIProxyAPI/v6/sdk/translator"
"golang.org/x/net/context" "golang.org/x/net/context"
) )
@@ -45,7 +45,7 @@ type BaseAPIHandler struct {
AuthManager *coreauth.Manager AuthManager *coreauth.Manager
// Cfg holds the current application configuration. // Cfg holds the current application configuration.
Cfg *config.Config Cfg *config.SDKConfig
} }
// NewBaseAPIHandlers creates a new API handlers instance. // NewBaseAPIHandlers creates a new API handlers instance.
@@ -57,7 +57,7 @@ type BaseAPIHandler struct {
// //
// Returns: // Returns:
// - *BaseAPIHandler: A new API handlers instance // - *BaseAPIHandler: A new API handlers instance
func NewBaseAPIHandlers(cfg *config.Config, authManager *coreauth.Manager) *BaseAPIHandler { func NewBaseAPIHandlers(cfg *config.SDKConfig, authManager *coreauth.Manager) *BaseAPIHandler {
return &BaseAPIHandler{ return &BaseAPIHandler{
Cfg: cfg, Cfg: cfg,
AuthManager: authManager, AuthManager: authManager,
@@ -70,7 +70,7 @@ func NewBaseAPIHandlers(cfg *config.Config, authManager *coreauth.Manager) *Base
// Parameters: // Parameters:
// - clients: The new slice of AI service clients // - clients: The new slice of AI service clients
// - cfg: The new application configuration // - cfg: The new application configuration
func (h *BaseAPIHandler) UpdateClients(cfg *config.Config) { h.Cfg = cfg } func (h *BaseAPIHandler) UpdateClients(cfg *config.SDKConfig) { h.Cfg = cfg }
// GetAlt extracts the 'alt' parameter from the request query string. // GetAlt extracts the 'alt' parameter from the request query string.
// It checks both 'alt' and '$alt' parameters and returns the appropriate value. // It checks both 'alt' and '$alt' parameters and returns the appropriate value.
@@ -133,7 +133,7 @@ func (h *BaseAPIHandler) GetContextWithCancel(handler interfaces.APIHandler, c *
// ExecuteWithAuthManager executes a non-streaming request via the core auth manager. // ExecuteWithAuthManager executes a non-streaming request via the core auth manager.
// This path is the only supported execution route. // This path is the only supported execution route.
func (h *BaseAPIHandler) ExecuteWithAuthManager(ctx context.Context, handlerType, modelName string, rawJSON []byte, alt string) ([]byte, *interfaces.ErrorMessage) { func (h *BaseAPIHandler) ExecuteWithAuthManager(ctx context.Context, handlerType, modelName string, rawJSON []byte, alt string) ([]byte, *interfaces.ErrorMessage) {
providers := util.GetProviderName(modelName, h.Cfg) providers := util.GetProviderName(modelName)
if len(providers) == 0 { if len(providers) == 0 {
return nil, &interfaces.ErrorMessage{StatusCode: http.StatusBadRequest, Error: fmt.Errorf("unknown provider for model %s", modelName)} return nil, &interfaces.ErrorMessage{StatusCode: http.StatusBadRequest, Error: fmt.Errorf("unknown provider for model %s", modelName)}
} }
@@ -157,7 +157,7 @@ func (h *BaseAPIHandler) ExecuteWithAuthManager(ctx context.Context, handlerType
// ExecuteCountWithAuthManager executes a non-streaming request via the core auth manager. // ExecuteCountWithAuthManager executes a non-streaming request via the core auth manager.
// This path is the only supported execution route. // This path is the only supported execution route.
func (h *BaseAPIHandler) ExecuteCountWithAuthManager(ctx context.Context, handlerType, modelName string, rawJSON []byte, alt string) ([]byte, *interfaces.ErrorMessage) { func (h *BaseAPIHandler) ExecuteCountWithAuthManager(ctx context.Context, handlerType, modelName string, rawJSON []byte, alt string) ([]byte, *interfaces.ErrorMessage) {
providers := util.GetProviderName(modelName, h.Cfg) providers := util.GetProviderName(modelName)
if len(providers) == 0 { if len(providers) == 0 {
return nil, &interfaces.ErrorMessage{StatusCode: http.StatusBadRequest, Error: fmt.Errorf("unknown provider for model %s", modelName)} return nil, &interfaces.ErrorMessage{StatusCode: http.StatusBadRequest, Error: fmt.Errorf("unknown provider for model %s", modelName)}
} }
@@ -181,7 +181,7 @@ func (h *BaseAPIHandler) ExecuteCountWithAuthManager(ctx context.Context, handle
// ExecuteStreamWithAuthManager executes a streaming request via the core auth manager. // ExecuteStreamWithAuthManager executes a streaming request via the core auth manager.
// This path is the only supported execution route. // This path is the only supported execution route.
func (h *BaseAPIHandler) ExecuteStreamWithAuthManager(ctx context.Context, handlerType, modelName string, rawJSON []byte, alt string) (<-chan []byte, <-chan *interfaces.ErrorMessage) { func (h *BaseAPIHandler) ExecuteStreamWithAuthManager(ctx context.Context, handlerType, modelName string, rawJSON []byte, alt string) (<-chan []byte, <-chan *interfaces.ErrorMessage) {
providers := util.GetProviderName(modelName, h.Cfg) providers := util.GetProviderName(modelName)
if len(providers) == 0 { if len(providers) == 0 {
errChan := make(chan *interfaces.ErrorMessage, 1) errChan := make(chan *interfaces.ErrorMessage, 1)
errChan <- &interfaces.ErrorMessage{StatusCode: http.StatusBadRequest, Error: fmt.Errorf("unknown provider for model %s", modelName)} errChan <- &interfaces.ErrorMessage{StatusCode: http.StatusBadRequest, Error: fmt.Errorf("unknown provider for model %s", modelName)}

View File

@@ -14,10 +14,10 @@ import (
"time" "time"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"github.com/router-for-me/CLIProxyAPI/v6/internal/api/handlers"
. "github.com/router-for-me/CLIProxyAPI/v6/internal/constant" . "github.com/router-for-me/CLIProxyAPI/v6/internal/constant"
"github.com/router-for-me/CLIProxyAPI/v6/internal/interfaces" "github.com/router-for-me/CLIProxyAPI/v6/internal/interfaces"
"github.com/router-for-me/CLIProxyAPI/v6/internal/registry" "github.com/router-for-me/CLIProxyAPI/v6/internal/registry"
"github.com/router-for-me/CLIProxyAPI/v6/sdk/api/handlers"
"github.com/tidwall/gjson" "github.com/tidwall/gjson"
"github.com/tidwall/sjson" "github.com/tidwall/sjson"
) )

View File

@@ -14,10 +14,10 @@ import (
"time" "time"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"github.com/router-for-me/CLIProxyAPI/v6/internal/api/handlers"
. "github.com/router-for-me/CLIProxyAPI/v6/internal/constant" . "github.com/router-for-me/CLIProxyAPI/v6/internal/constant"
"github.com/router-for-me/CLIProxyAPI/v6/internal/interfaces" "github.com/router-for-me/CLIProxyAPI/v6/internal/interfaces"
"github.com/router-for-me/CLIProxyAPI/v6/internal/registry" "github.com/router-for-me/CLIProxyAPI/v6/internal/registry"
"github.com/router-for-me/CLIProxyAPI/v6/sdk/api/handlers"
"github.com/tidwall/gjson" "github.com/tidwall/gjson"
) )

14
sdk/config/config.go Normal file
View File

@@ -0,0 +1,14 @@
// Package config provides configuration management for the CLI Proxy API server.
// It handles loading and parsing YAML configuration files, and provides structured
// access to application settings including server port, authentication directory,
// debug settings, proxy configuration, and API keys.
package config
// SDKConfig represents the application's configuration, loaded from a YAML file.
type SDKConfig struct {
// ProxyURL is the URL of an optional proxy server to use for outbound requests.
ProxyURL string `yaml:"proxy-url" json:"proxy-url"`
// RequestLog enables or disables detailed request logging functionality.
RequestLog bool `yaml:"request-log" json:"request-log"`
}