util

package
v5.2.6 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 21, 2025 License: MIT Imports: 19 Imported by: 0

Documentation

Overview

Package util provides utility functions used across the CLIProxyAPI application. These functions handle common tasks such as determining AI service providers from model names and managing HTTP proxies.

Package util provides utility functions for the CLI Proxy API server. It includes helper functions for proxy configuration, HTTP client setup, log level management, and other common operations used across the application.

Package util provides helper functions for SSH tunnel instructions and network-related tasks. This includes detecting the appropriate IP address and printing commands to help users connect to the local server from a remote machine.

Package util provides utility functions for the CLI Proxy API server. It includes helper functions for JSON manipulation, proxy configuration, and other common operations used across the application.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CookieSnapshotPath added in v5.2.1

func CookieSnapshotPath(mainPath string) string

CookieSnapshotPath derives the cookie snapshot file path from the main token JSON path. It replaces the .json suffix with .cookie, or appends .cookie if missing.

func FixJSON

func FixJSON(input string) string

FixJSON converts non-standard JSON that uses single quotes for strings into RFC 8259-compliant JSON by converting those single-quoted strings to double-quoted strings with proper escaping.

Examples:

{'a': 1, 'b': '2'}      => {"a": 1, "b": "2"}
{"t": 'He said "hi"'} => {"t": "He said \"hi\""}

Rules:

  • Existing double-quoted JSON strings are preserved as-is.
  • Single-quoted strings are converted to double-quoted strings.
  • Inside converted strings, any double quote is escaped (\").
  • Common backslash escapes (\n, \r, \t, \b, \f, \\) are preserved.
  • \' inside single-quoted strings becomes a literal ' in the output (no escaping needed inside double quotes).
  • Unicode escapes (\uXXXX) inside single-quoted strings are forwarded.
  • The function does not attempt to fix other non-JSON features beyond quotes.

func GetIPAddress

func GetIPAddress() string

GetIPAddress attempts to find the best-available IP address. It first tries to get the public IP address, and if that fails, it falls back to getting the local outbound IP address.

Returns:

  • string: The determined IP address (preferring public IPv4)

func GetOpenAICompatibilityConfig

func GetOpenAICompatibilityConfig(alias string, cfg *config.Config) (*config.OpenAICompatibility, *config.OpenAICompatibilityModel)

GetOpenAICompatibilityConfig returns the OpenAI compatibility configuration and model details for the given alias.

Parameters:

  • alias: The model alias to find configuration for
  • cfg: The application configuration containing OpenAI compatibility settings

Returns:

  • *config.OpenAICompatibility: The matching compatibility configuration, or nil if not found
  • *config.OpenAICompatibilityModel: The matching model configuration, or nil if not found

func GetProviderName

func GetProviderName(modelName string, cfg *config.Config) string

GetProviderName determines the AI service provider based on the model name. It analyzes the model name string to identify which service provider it belongs to. First checks for OpenAI compatibility aliases, then falls back to standard provider detection.

Supported providers:

  • "gemini" for Google's Gemini models
  • "gpt" for OpenAI's GPT models
  • "claude" for Anthropic's Claude models
  • "qwen" for Alibaba's Qwen models
  • "openai-compatibility" for external OpenAI-compatible providers
  • "unknow" for unrecognized model names

Parameters:

  • modelName: The name of the model to identify the provider for.
  • cfg: The application configuration containing OpenAI compatibility settings.

Returns:

  • string: The name of the provider.

func HideAPIKey

func HideAPIKey(apiKey string) string

HideAPIKey obscures an API key for logging purposes, showing only the first and last few characters.

Parameters:

  • apiKey: The API key to hide.

Returns:

  • string: The obscured API key.

func InArray

func InArray(hystack []string, needle string) bool

InArray checks if a string exists in a slice of strings. It iterates through the slice and returns true if the target string is found, otherwise it returns false.

Parameters:

  • hystack: The slice of strings to search in
  • needle: The string to search for

Returns:

  • bool: True if the string is found, false otherwise

func IsOpenAICompatibilityAlias

func IsOpenAICompatibilityAlias(modelName string, cfg *config.Config) bool

IsOpenAICompatibilityAlias checks if the given model name is an alias configured for OpenAI compatibility routing.

Parameters:

  • modelName: The model name to check
  • cfg: The application configuration containing OpenAI compatibility settings

Returns:

  • bool: True if the model name is an OpenAI compatibility alias, false otherwise

func IsRegularFile added in v5.2.1

func IsRegularFile(path string) bool

IsRegularFile reports whether the given path exists and is a regular file.

func PrintSSHTunnelInstructions

func PrintSSHTunnelInstructions(port int)

PrintSSHTunnelInstructions detects the IP address and prints SSH tunnel instructions for the user to connect to the local OAuth callback server from a remote machine.

Parameters:

  • port: The local port number for the SSH tunnel

func ReadAuthFilePreferSnapshot added in v5.2.2

func ReadAuthFilePreferSnapshot(path string) ([]byte, error)

ReadAuthFilePreferSnapshot returns the first non-empty auth payload preferring snapshots.

func ReadAuthFileWithRetry added in v5.2.2

func ReadAuthFileWithRetry(path string, attempts int, delay time.Duration) ([]byte, error)

ReadAuthFileWithRetry attempts to read an auth file multiple times and prefers cookie snapshots.

func ReadJSON added in v5.2.1

func ReadJSON(path string, v any) error

ReadJSON reads and unmarshals a JSON file into v. Returns os.ErrNotExist if the file does not exist.

func RemoveCookieSnapshots added in v5.2.1

func RemoveCookieSnapshots(mainPath string)

RemoveCookieSnapshots removes the snapshot file if it exists.

func RemoveFile added in v5.2.1

func RemoveFile(path string) error

RemoveFile removes the file if it exists.

func RenameKey

func RenameKey(jsonStr, oldKeyPath, newKeyPath string) (string, error)

RenameKey renames a key in a JSON string by moving its value to a new key path and then deleting the old key path.

Parameters:

  • jsonStr: The JSON string to modify
  • oldKeyPath: The dot-notation path to the key that should be renamed
  • newKeyPath: The dot-notation path where the value should be moved to

Returns:

  • string: The modified JSON string with the key renamed
  • error: An error if the operation fails

The function performs the rename in two steps: 1. Sets the value at the new key path 2. Deletes the old key path

func SanitizeSchemaForGemini added in v5.1.29

func SanitizeSchemaForGemini(schemaJSON string) (string, error)

SanitizeSchemaForGemini removes JSON Schema fields that are incompatible with Gemini API to prevent "Proto field is not repeating, cannot start list" errors.

Parameters:

  • schemaJSON: The JSON schema string to sanitize

Returns:

  • string: The sanitized schema string
  • error: An error if the operation fails

This function removes the following incompatible fields: - additionalProperties: Not supported in Gemini function declarations - $schema: JSON Schema meta-schema identifier, not needed for API - allOf/anyOf/oneOf: Union type constructs not supported - exclusiveMinimum/exclusiveMaximum: Advanced validation constraints - patternProperties: Advanced property pattern matching - dependencies: Property dependencies not supported - type arrays: Converts ["string", "null"] to just "string"

func SetLogLevel

func SetLogLevel(cfg *config.Config)

SetLogLevel configures the logrus log level based on the configuration. It sets the log level to DebugLevel if debug mode is enabled, otherwise to InfoLevel.

func SetProxy

func SetProxy(cfg *config.Config, httpClient *http.Client) *http.Client

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 to route requests through the configured proxy server.

func TryReadCookieSnapshotInto added in v5.2.1

func TryReadCookieSnapshotInto(mainPath string, v any) (bool, error)

TryReadCookieSnapshotInto tries to read a cookie snapshot into v using the .cookie suffix. Returns (true, nil) when a snapshot was decoded, or (false, nil) when none exists.

func Walk

func Walk(value gjson.Result, path, field string, paths *[]string)

Walk recursively traverses a JSON structure to find all occurrences of a specific field. It builds paths to each occurrence and adds them to the provided paths slice.

Parameters:

  • value: The gjson.Result object to traverse
  • path: The current path in the JSON structure (empty string for root)
  • field: The field name to search for
  • paths: Pointer to a slice where found paths will be stored

The function works recursively, building dot-notation paths to each occurrence of the specified field throughout the JSON structure.

func WriteCookieSnapshot added in v5.2.1

func WriteCookieSnapshot(mainPath string, v any) error

WriteCookieSnapshot writes v to the snapshot path derived from mainPath using the .cookie suffix.

func WriteJSON added in v5.2.1

func WriteJSON(path string, v any) error

WriteJSON marshals v as JSON and writes to path, creating parent directories as needed.

Types

type FlushOption added in v5.2.1

type FlushOption[T any] func(*FlushOptions[T])

FlushOption mutates FlushOptions.

func WithFallback added in v5.2.1

func WithFallback[T any](fn func() *T) FlushOption[T]

WithFallback provides fallback payload when no snapshot exists.

func WithMutate added in v5.2.1

func WithMutate[T any](fn func(*T)) FlushOption[T]

WithMutate allows last-minute mutation of the payload before writing main file.

type FlushOptions added in v5.2.1

type FlushOptions[T any] struct {
	Fallback func() *T
	Mutate   func(*T)
}

FlushOptions configure Flush behaviour.

type Hooks added in v5.2.1

type Hooks[T any] struct {
	// Apply merges snapshot data into the in-memory store during Apply().
	// Defaults to overwriting the store with the snapshot contents.
	Apply func(store *T, snapshot *T)

	// Snapshot prepares the payload to persist during Persist().
	// Defaults to cloning the store value.
	Snapshot func(store *T) *T

	// Merge chooses which data to flush when a snapshot exists.
	// Defaults to using the snapshot payload as-is.
	Merge func(store *T, snapshot *T) *T

	// WriteMain persists the merged payload into the canonical token path.
	// Defaults to WriteJSON.
	WriteMain func(path string, data *T) error
}

Hooks provide customization points for snapshot lifecycle operations.

type Manager added in v5.2.1

type Manager[T any] struct {
	// contains filtered or unexported fields
}

Manager orchestrates cookie snapshot lifecycle for token storages.

func NewManager added in v5.2.1

func NewManager[T any](mainPath string, store *T, hooks Hooks[T]) *Manager[T]

NewManager constructs a Manager bound to mainPath and store.

func (*Manager[T]) Apply added in v5.2.1

func (m *Manager[T]) Apply() (bool, error)

Apply loads snapshot data into the in-memory store if available. Returns true when a snapshot was applied.

func (*Manager[T]) Flush added in v5.2.1

func (m *Manager[T]) Flush(options ...FlushOption[T]) error

Flush commits snapshot (or fallback) into the main token file and removes the snapshot.

func (*Manager[T]) Persist added in v5.2.1

func (m *Manager[T]) Persist() error

Persist writes the current store state to the snapshot file.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL