### Configuration Options for Singgen (Go) Source: https://pkg.go.dev/github.com/sixproxy/singgen/pkg/singgen?utm_source=chatgpt.com/index_utm_source=chatgpt.com Provides examples of various functional options available for configuring the singgen library. These options cover template selection, platform targeting, network settings, output formatting, logging, and performance tuning. ```Go // Template and platform singgen.WithTemplate("v1.12") singgen.WithPlatform("linux") // Network settings singgen.WithHTTPTimeout(30 * time.Second) singgen.WithMirrorURL("https://custom-mirror.com") singgen.WithDNSServer("1.1.1.1") singgen.WithClientSubnet("202.101.170.1/24") // Output settings singgen.WithOutputFormat("yaml") singgen.WithEmojiRemoval(true) singgen.WithExternalController("127.0.0.1:9095") // Logging singgen.WithLogger(logger) // Platform-specific defaults singgen.WithLinuxDefaults() singgen.WithDarwinDefaults() singgen.WithIOSDefaults() // Performance tuning singgen.WithPerformanceOptimized() singgen.WithStrictSecurity() ``` -------------------------------- ### Apply General Defaults Option in Go Source: https://pkg.go.dev/github.com/sixproxy/singgen/pkg/singgen?utm_source=chatgpt.com/index_utm_source=chatgpt.com A functional option that applies sensible default settings suitable for common use cases. This provides a convenient starting point for generation. ```go func WithDefaults() Option ``` -------------------------------- ### Generate Configuration using High-Level API (Go) Source: https://pkg.go.dev/github.com/sixproxy/singgen/pkg/singgen?utm_source=chatgpt.com/index_utm_source=chatgpt.com Demonstrates using the high-level API to generate a sing-box configuration from a subscription URL. It handles the complete generation process with sensible defaults. Dependencies include the context package for cancellation and timeouts. ```Go config, err := singgen.GenerateConfig(ctx, "https://example.com/sub", singgen.WithTemplate("v1.12"), singgen.WithPlatform("linux")) // Get configuration as bytes data, err := singgen.GenerateConfigBytes(ctx, "subscription.txt", singgen.WithOutputFormat("yaml")) // Just parse nodes without generating configuration nodes, err := singgen.ParseNodes(ctx, "https://example.com/sub") ``` -------------------------------- ### Generate Configuration using Mid-Level API (Go) Source: https://pkg.go.dev/github.com/sixproxy/singgen/pkg/singgen?utm_source=chatgpt.com/index_utm_source=chatgpt.com Illustrates the mid-level API for more control over configuration generation using the Generator type. Allows customization of templates, platform, timeouts, and logging. Dependencies include the time package for durations and a logger implementation. ```Go generator := singgen.NewGenerator( singgen.WithTemplate("v1.12"), singgen.WithPlatform("darwin"), singgen.WithHTTPTimeout(30*time.Second), singgen.WithLogger(logger)) config, err := generator.Generate(ctx, "subscription.txt") nodes, err := generator.ParseNodes(ctx, "subscription.txt") templates, err := generator.GetAvailableTemplates() ``` -------------------------------- ### Create New Pipeline in Go Source: https://pkg.go.dev/github.com/sixproxy/singgen/pkg/singgen?utm_source=chatgpt.com/index_utm_source=chatgpt.com Constructs a new Pipeline instance with the specified PipelineOptions. This is the entry point for using the low-level pipeline API. ```go func NewPipeline(opts ...PipelineOption) *Pipeline ``` -------------------------------- ### Create Streaming Pipeline with NewStreamingPipeline Source: https://pkg.go.dev/github.com/sixproxy/singgen/pkg/singgen?utm_source=chatgpt.com/index_utm_source=chatgpt.com Initializes a new StreamingPipeline instance, which is used for processing large subscription files in a streaming fashion. Options can be provided to customize its behavior. ```go streamingPipeline := singgen.NewStreamingPipeline(opts ...PipelineOption) ``` -------------------------------- ### Execute Pipeline as Bytes with Pipeline.ExecuteBytes Source: https://pkg.go.dev/github.com/sixproxy/singgen/pkg/singgen?utm_source=chatgpt.com/index_utm_source=chatgpt.com Executes the pipeline and returns the generated configuration as a byte slice. This is useful when the output format is known and direct byte handling is preferred. ```go pipeline := singgen.NewPipeline(opts ...PipelineOption) byteConfig, err := pipeline.ExecuteBytes(ctx, source) ``` -------------------------------- ### Execute Pipeline using Low-Level API (Go) Source: https://pkg.go.dev/github.com/sixproxy/singgen/pkg/singgen?utm_source=chatgpt.com/index_utm_source=chatgpt.com Shows the low-level API for maximum control via the Pipeline type, enabling custom component injection. Allows executing individual steps like fetching, parsing, or transforming data. Dependencies include custom fetcher, parser, and transformer implementations. ```Go pipeline := singgen.NewPipeline( singgen.WithCustomFetcher(myFetcher), singgen.WithCustomParser(myParser), singgen.WithCustomTransformer(myTransformer)) result, err := pipeline.Execute(ctx, "https://example.com/sub") // result contains detailed metadata about the generation process // Execute individual steps data, err := pipeline.FetchOnly(ctx, "subscription.txt") nodes, err := pipeline.ParseOnly(ctx, "subscription.txt") outbounds, err := pipeline.TransformOnly(ctx, "subscription.txt") ``` -------------------------------- ### Context Support for Operations (Go) Source: https://pkg.go.dev/github.com/sixproxy/singgen/pkg/singgen?utm_source=chatgpt.com/index_utm_source=chatgpt.com Demonstrates how to use `context.Context` for managing cancellation and timeouts in singgen operations. This is crucial for preventing resource leaks and handling long-running requests gracefully. Dependencies include the `context` package. ```Go ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel() config, err := singgen.GenerateConfig(ctx, url) if errors.Is(err, context.DeadlineExceeded) { // Handle timeout } ``` -------------------------------- ### Create a Context-Aware Fetcher (Go) Source: https://pkg.go.dev/github.com/sixproxy/singgen/pkg/singgen?utm_source=chatgpt.com/index_utm_source=chatgpt.com The NewContextFetcher function instantiates a ContextFetcher. This fetcher is designed to retrieve data from a given source in a context-aware manner, automatically detecting the source type. It requires GenerateOptions to configure its behavior, such as network timeouts or mirror URLs. ```Go func NewContextFetcher(options GenerateOptions) ContextFetcher ``` -------------------------------- ### Initialize a Generator with Options (Go) Source: https://pkg.go.dev/github.com/sixproxy/singgen/pkg/singgen?utm_source=chatgpt.com/index_utm_source=chatgpt.com NewGenerator creates a new instance of the Generator struct, which provides a mid-level API for configuration generation. It accepts variadic Option functions to configure the generator's behavior, allowing for fine-grained control over the generation pipeline. This is useful for more complex scenarios where the default generation process needs modification. ```Go func NewGenerator(opts ...Option) *Generator ``` -------------------------------- ### Generate Configuration as Bytes (Go) Source: https://pkg.go.dev/github.com/sixproxy/singgen/pkg/singgen?utm_source=chatgpt.com/index_utm_source=chatgpt.com The GenerateConfigBytes function generates a sing-box configuration and returns it as a byte slice. It accepts a context for cancellation, a source string for the configuration data, and variadic options to customize the generation process. This function is useful when the configuration needs to be directly manipulated or transmitted as raw data. ```Go func GenerateConfigBytes(ctx context.Context, source string, opts ...Option) ([]byte, error) ``` -------------------------------- ### Create a Context-Aware Transformer (Go) Source: https://pkg.go.dev/github.com/sixproxy/singgen/pkg/singgen?utm_source=chatgpt.com/index_utm_source=chatgpt.com This function, NewContextTransformer, initializes a ContextTransformer. This transformer takes a slice of model.Node and converts them into a slice of transformer.Outbound, which is a format suitable for sing-box configurations. It leverages GenerateOptions to customize the transformation process, potentially affecting how nodes are mapped or filtered. ```Go func NewContextTransformer(options GenerateOptions) ContextTransformer ``` -------------------------------- ### Apply Pipeline Options (Go) Source: https://pkg.go.dev/github.com/sixproxy/singgen/pkg/singgen?utm_source=chatgpt.com/index_utm_source=chatgpt.com WithPipelineOptions applies GenerateOptions to the pipeline. It accepts a variable number of Option arguments and returns a PipelineOption. ```Go func WithPipelineOptions(opts ...Option) PipelineOption { // Implementation details omitted for brevity } ``` -------------------------------- ### Perform Full Configuration Generation (Go) Source: https://pkg.go.dev/github.com/sixproxy/singgen/pkg/singgen?utm_source=chatgpt.com/index_utm_source=chatgpt.com The Generate method on the Generator struct orchestrates the complete configuration generation process. It takes a context and a source string, then applies the configured fetchers, parsers, and transformers to produce a final Config object. This method encapsulates the entire workflow from raw data to a structured configuration. ```Go func (g *Generator) Generate(ctx context.Context, source string) (*Config, error) ``` -------------------------------- ### Execute Full Pipeline in Go Source: https://pkg.go.dev/github.com/sixproxy/singgen/pkg/singgen?utm_source=chatgpt.com/index_utm_source=chatgpt.com Runs the entire pipeline, from fetching source data to generating the final output. It takes a context and source string, returning the pipeline result or an error. ```go func (p *Pipeline) Execute(ctx context.Context, source string) (*PipelineResult, error) ``` -------------------------------- ### Generate Configuration with Low-Level API Source: https://pkg.go.dev/github.com/sixproxy/singgen/pkg/singgen?utm_source=chatgpt.com/index_utm_source=chatgpt.com Provides maximum control over configuration generation using the low-level API. Users can supply custom fetchers and parsers for specialized needs. ```go pipeline := singgen.NewPipeline( singgen.WithCustomFetcher(myFetcher), singgen.WithCustomParser(myParser)) result, err := pipeline.Execute(ctx, source) ``` -------------------------------- ### Create New Streaming Pipeline (Go) Source: https://pkg.go.dev/github.com/sixproxy/singgen/pkg/singgen?utm_source=chatgpt.com/index_utm_source=chatgpt.com NewStreamingPipeline constructs a new streaming pipeline instance. It accepts a variable number of PipelineOption arguments to configure the pipeline. ```Go func NewStreamingPipeline(opts ...PipelineOption) *StreamingPipeline { // Implementation details omitted for brevity } ``` -------------------------------- ### Generate Configuration with High-Level API Source: https://pkg.go.dev/github.com/sixproxy/singgen/pkg/singgen?utm_source=chatgpt.com/index_utm_source=chatgpt.com Generates a sing-box configuration using the high-level API. This is the recommended approach for most users. It allows specifying options like template version and target platform. ```go config, err := singgen.GenerateConfig(ctx, "https://example.com/sub", singgen.WithTemplate("v1.12"), singgen.WithPlatform("linux")) ``` -------------------------------- ### Apply macOS Defaults Option in Go Source: https://pkg.go.dev/github.com/sixproxy/singgen/pkg/singgen?utm_source=chatgpt.com/index_utm_source=chatgpt.com A functional option that applies default settings optimized for the macOS platform. This simplifies configuration for users targeting Apple devices. ```go func WithDarwinDefaults() Option ``` -------------------------------- ### Execute Pipeline with Pipeline.Execute Source: https://pkg.go.dev/github.com/sixproxy/singgen/pkg/singgen?utm_source=chatgpt.com/index_utm_source=chatgpt.com Executes the full pipeline for configuration generation, including fetching, parsing, and transforming data. Returns a PipelineResult containing the generated configuration. ```go pipeline := singgen.NewPipeline(opts ...PipelineOption) result, err := pipeline.Execute(ctx, source) ``` -------------------------------- ### Pipeline Configuration Options Source: https://pkg.go.dev/github.com/sixproxy/singgen/pkg/singgen?utm_source=chatgpt.com/index_utm_source=chatgpt.com These options allow for customization of the Singgen pipeline's behavior, such as setting custom renderers, templates, transformers, and applying additional generation options. ```APIDOC ## Pipeline Configuration Options ### Description Configuration functions to customize the Singgen pipeline. ### Method N/A (These are constructor options) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```go // Example usage: pipeline := NewStreamingPipeline( WithCustomRenderer(myRenderer), WithCustomTemplate(myTemplate), WithCustomTransformer(myTransformer), WithPipelineOptions(option1, option2) ) ``` ### Response #### Success Response (N/A) N/A #### Response Example N/A ``` -------------------------------- ### Apply Linux Defaults Option in Go Source: https://pkg.go.dev/github.com/sixproxy/singgen/pkg/singgen?utm_source=chatgpt.com/index_utm_source=chatgpt.com A functional option that applies default settings optimized for the Linux platform. This simplifies configuration for Linux environments. ```go func WithLinuxDefaults() Option ``` -------------------------------- ### Error Handling with Specific Error Types (Go) Source: https://pkg.go.dev/github.com/sixproxy/singgen/pkg/singgen?utm_source=chatgpt.com/index_utm_source=chatgpt.com Illustrates structured error handling in singgen by checking for specific error types using `errors.Is`. This allows for more granular control over how different failure scenarios are managed. Dependencies include the `errors` package. ```Go config, err := singgen.GenerateConfig(ctx, source) if err != nil { switch { case errors.Is(err, singgen.ErrEmptySource): // Handle empty source case errors.Is(err, singgen.ErrNoValidNodes): // Handle no valid nodes case errors.Is(err, singgen.ErrUnsupportedFormat): // Handle unsupported format default: // Handle other errors } } ``` -------------------------------- ### Apply iOS Defaults Option in Go Source: https://pkg.go.dev/github.com/sixproxy/singgen/pkg/singgen?utm_source=chatgpt.com/index_utm_source=chatgpt.com A functional option that applies default settings optimized for the iOS platform. This streamlines configuration for iOS-specific deployments. ```go func WithIOSDefaults() Option ``` -------------------------------- ### Create a Context-Aware Parser (Go) Source: https://pkg.go.dev/github.com/sixproxy/singgen/pkg/singgen?utm_source=chatgpt.com/index_utm_source=chatgpt.com NewContextParser creates a ContextParser instance, which is responsible for parsing data into a list of model.Node. It supports automatic format detection and can also parse with an explicit format hint. The parser utilizes GenerateOptions for its configuration, influencing how it handles different data formats and potential parsing errors. ```Go func NewContextParser(options GenerateOptions) ContextParser ``` -------------------------------- ### Set Custom Template for Pipeline (Go) Source: https://pkg.go.dev/github.com/sixproxy/singgen/pkg/singgen?utm_source=chatgpt.com/index_utm_source=chatgpt.com WithCustomTemplate enables setting a custom template for the pipeline. It accepts a template.Template object and returns a PipelineOption. ```Go func WithCustomTemplate(template template.Template) PipelineOption { // Implementation details omitted for brevity } ``` -------------------------------- ### Configuration Generation API Source: https://pkg.go.dev/github.com/sixproxy/singgen/pkg/singgen?utm_source=chatgpt.com/index_utm_source=chatgpt.com Provides high-level functions for generating sing-box configurations from various sources. ```APIDOC ## POST /generate/config ### Description Generates a sing-box configuration in byte format from a given source URL or path. ### Method POST ### Endpoint `/generate/config` ### Parameters #### Query Parameters - **source** (string) - Required - The URL or path to the configuration source. - **opts** (*Option) - Optional - Options to customize the generation process. ### Request Body This endpoint does not typically use a request body for the source, but options can be passed as query parameters or through a dedicated options object if the API were designed differently. ### Request Example ```go ctx := context.Background() sourceURL := "http://example.com/proxies.txt" configBytes, err := singgen.GenerateConfigBytes(ctx, sourceURL) if err != nil { log.Fatal(err) } fmt.Println(string(configBytes)) ``` ### Response #### Success Response (200) - **[]byte** - The generated configuration as a byte slice. #### Response Example ```json { "proxies": [ { "name": "proxy1", "server": "1.2.3.4", "port": 8080, "type": "socks5" } ] } ``` ## POST /generate/config/object ### Description Generates a sing-box configuration object directly. ### Method POST ### Endpoint `/generate/config/object` ### Parameters #### Query Parameters - **source** (string) - Required - The URL or path to the configuration source. - **opts** (*Option) - Optional - Options to customize the generation process. ### Request Body Similar to `GenerateConfigBytes`, the source is typically a query parameter. ### Request Example ```go ctx := context.Background() sourceURL := "http://example.com/proxies.txt" config, err := singgen.GenerateConfig(ctx, sourceURL) if err != nil { log.Fatal(err) } fmt.Printf("%+v\n", config) ``` ### Response #### Success Response (200) - **Config** - A pointer to the generated `Config` object. #### Response Example ```json { "proxies": [ { "name": "proxy1", "server": "1.2.3.4", "port": 8080, "type": "socks5" } ] } ``` ``` -------------------------------- ### Fetch Only Pipeline Step in Go Source: https://pkg.go.dev/github.com/sixproxy/singgen/pkg/singgen?utm_source=chatgpt.com/index_utm_source=chatgpt.com Performs only the fetch step of the pipeline, retrieving the raw source data. It returns the data as a byte slice or an error. ```go func (p *Pipeline) FetchOnly(ctx context.Context, source string) ([]byte, error) ``` -------------------------------- ### Generate Configuration Object (Go) Source: https://pkg.go.dev/github.com/sixproxy/singgen/pkg/singgen?utm_source=chatgpt.com/index_utm_source=chatgpt.com GenerateConfig provides a high-level API for creating sing-box configurations. It offers a straightforward interface with sensible defaults, while also allowing for detailed customization through options. The function returns a pointer to a Config object and an error if the generation process fails. This is the primary function for generating configurations in a structured format. ```Go func GenerateConfig(ctx context.Context, source string, opts ...Option) (*Config, error) ``` -------------------------------- ### Fetch Only with Pipeline.FetchOnly Source: https://pkg.go.dev/github.com/sixproxy/singgen/pkg/singgen?utm_source=chatgpt.com/index_utm_source=chatgpt.com Fetches subscription data from the source without parsing or transforming it. Returns the raw subscription data as a byte slice. ```go pipeline := singgen.NewPipeline(opts ...PipelineOption) rawData, err := pipeline.FetchOnly(ctx, source) ``` -------------------------------- ### Set Custom Renderer for Pipeline (Go) Source: https://pkg.go.dev/github.com/sixproxy/singgen/pkg/singgen?utm_source=chatgpt.com/index_utm_source=chatgpt.com WithCustomRenderer allows setting a custom renderer for the pipeline. This function takes a renderer.Renderer as an argument and returns a PipelineOption. ```Go func WithCustomRenderer(renderer renderer.Renderer) PipelineOption { // Implementation details omitted for brevity } ``` -------------------------------- ### Set Mirror URL Option in Go Source: https://pkg.go.dev/github.com/sixproxy/singgen/pkg/singgen?utm_source=chatgpt.com/index_utm_source=chatgpt.com A functional option to specify a mirror URL for downloading rule sets. This can improve download speeds or provide redundancy. ```go func WithMirrorURL(url string) Option ``` -------------------------------- ### Apply Performance Optimized Settings Option in Go Source: https://pkg.go.dev/github.com/sixproxy/singgen/pkg/singgen?utm_source=chatgpt.com/index_utm_source=chatgpt.com A functional option that applies settings optimized for performance. This may adjust various parameters to prioritize speed and efficiency. ```go func WithPerformanceOptimized() Option ``` -------------------------------- ### Generate Configuration with Mid-Level API Source: https://pkg.go.dev/github.com/sixproxy/singgen/pkg/singgen?utm_source=chatgpt.com/index_utm_source=chatgpt.com Generates a sing-box configuration using the mid-level API, offering more control than the high-level API. It allows customization of options like logger and HTTP timeout. ```go generator := singgen.NewGenerator( singgen.WithLogger(logger), singgen.WithHTTPTimeout(30*time.Second)) config, err := generator.Generate(ctx, source) ``` -------------------------------- ### Core Components and Utilities Source: https://pkg.go.dev/github.com/sixproxy/singgen/pkg/singgen?utm_source=chatgpt.com/index_utm_source=chatgpt.com Provides interfaces and functions for fetching, parsing, and transforming proxy node data. ```APIDOC ## Interfaces ### ContextFetcher #### Description Provides context-aware data fetching with automatic source type detection. #### Methods - **Fetch(ctx context.Context, source string) ([]byte, error)**: Fetches data from the given source. ### ContextParser #### Description Provides context-aware parsing with smart format detection. #### Methods - **DetectFormat(ctx context.Context, data []byte) string**: Detects the format of the provided data. - **Parse(ctx context.Context, data []byte) ([]model.Node, error)**: Parses the data into a slice of `model.Node`. - **ParseWithHint(ctx context.Context, data []byte, formatHint string) ([]model.Node, error)**: Parses the data with an optional format hint. ### ContextTransformer #### Description Provides context-aware node transformation. #### Methods - **Transform(ctx context.Context, nodes []model.Node) ([]transformer.Outbound, error)**: Transforms a slice of `model.Node` into `transformer.Outbound`. ## Functions ### NewContextFetcher #### Description Creates a new context-aware fetcher. #### Parameters - **options** (GenerateOptions) - Options to configure the fetcher. ### NewContextParser #### Description Creates a new context-aware parser. #### Parameters - **options** (GenerateOptions) - Options to configure the parser. ### NewContextTransformer #### Description Creates a new context-aware transformer. #### Parameters - **options** (GenerateOptions) - Options to configure the transformer. ### NewGenerator #### Description Creates a new Generator with the specified options. #### Parameters - **opts** (...Option) - Options to configure the generator. ### Generator.Generate #### Description Performs the complete generation process from source to configuration. #### Parameters - **ctx** (context.Context) - The context for the operation. - **source** (string) - The configuration source. #### Returns - **(*Config, error)** - The generated configuration and any error encountered. ### Generator.GetAvailableTemplates #### Description Returns a list of available template versions. #### Returns - **([]string, error)** - A slice of template names and any error encountered. ### Generator.ParseNodes #### Description Extracts and parses nodes from a source. #### Parameters - **ctx** (context.Context) - The context for the operation. - **source** (string) - The configuration source. #### Returns - **([]Node, error)** - A slice of parsed nodes and any error encountered. ``` -------------------------------- ### Set Output Format Option in Go Source: https://pkg.go.dev/github.com/sixproxy/singgen/pkg/singgen?utm_source=chatgpt.com/index_utm_source=chatgpt.com A functional option to set the desired output format for the generated configuration, supporting 'json' or 'yaml'. ```go func WithOutputFormat(format string) Option ``` -------------------------------- ### Set Target Platform Option in Go Source: https://pkg.go.dev/github.com/sixproxy/singgen/pkg/singgen?utm_source=chatgpt.com/index_utm_source=chatgpt.com A functional option to specify the target platform for which the configuration is being generated (e.g., 'linux', 'darwin', 'ios'). ```go func WithPlatform(platform string) Option ``` -------------------------------- ### Execute Pipeline to Bytes in Go Source: https://pkg.go.dev/github.com/sixproxy/singgen/pkg/singgen?utm_source=chatgpt.com/index_utm_source=chatgpt.com Executes the pipeline and returns the final output as a byte slice. This is useful when the output needs to be processed further as raw data. ```go func (p *Pipeline) ExecuteBytes(ctx context.Context, source string) ([]byte, error) ``` -------------------------------- ### Retrieve Available Template Versions (Go) Source: https://pkg.go.dev/github.com/sixproxy/singgen/pkg/singgen?utm_source=chatgpt.com/index_utm_source=chatgpt.com GetAvailableTemplates is a method on the Generator struct that returns a list of all template versions currently supported by the singgen package. This information is valuable for users who need to specify a particular template version during configuration generation or to understand the available customization options. ```Go func (g *Generator) GetAvailableTemplates() ([]string, error) ``` -------------------------------- ### Configure Generation Process with Options in Go Source: https://pkg.go.dev/github.com/sixproxy/singgen/pkg/singgen?utm_source=chatgpt.com/index_utm_source=chatgpt.com Defines the Option type, a function type used for configuring the generation process via the functional options pattern. This allows for flexible and readable configuration of generation parameters. ```go type Option func(*GenerateOptions) ``` -------------------------------- ### Set Template Version Option in Go Source: https://pkg.go.dev/github.com/sixproxy/singgen/pkg/singgen?utm_source=chatgpt.com/index_utm_source=chatgpt.com A functional option to specify the template version to use for generation (e.g., 'v1.12', 'v1.13'). This allows control over the output structure and features. ```go func WithTemplate(version string) Option ``` -------------------------------- ### Generate Config Bytes with GenerateConfigBytes Source: https://pkg.go.dev/github.com/sixproxy/singgen/pkg/singgen?utm_source=chatgpt.com/index_utm_source=chatgpt.com Generates a sing-box configuration directly as a byte slice. This function is useful for scenarios where the configuration needs to be directly written to a file or transmitted. ```go byteConfig, err := singgen.GenerateConfigBytes(ctx, source, opts ...Option) ``` -------------------------------- ### Apply Strict Security Settings Option in Go Source: https://pkg.go.dev/github.com/sixproxy/singgen/pkg/singgen?utm_source=chatgpt.com/index_utm_source=chatgpt.com A functional option that applies security-focused settings. This may enable stricter validation or security measures during generation. ```go func WithStrictSecurity() Option ``` -------------------------------- ### Set DNS Server Option in Go Source: https://pkg.go.dev/github.com/sixproxy/singgen/pkg/singgen?utm_source=chatgpt.com/index_utm_source=chatgpt.com A functional option to specify the DNS server address to be used during node generation. This is useful for custom DNS configurations or testing. ```go func WithDNSServer(server string) Option ``` -------------------------------- ### StreamingPipeline Source: https://pkg.go.dev/github.com/sixproxy/singgen/pkg/singgen?utm_source=chatgpt.com/index_utm_source=chatgpt.com The StreamingPipeline provides capabilities for processing large subscription files by streaming results in batches. ```APIDOC ## StreamingPipeline ### Description Provides streaming capabilities for processing large subscription files. ### Method N/A (This is a type definition) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example N/A ### Response #### Success Response (N/A) N/A #### Response Example N/A ``` ```APIDOC ## NewStreamingPipeline ### Description Creates a new streaming pipeline with the specified options. ### Method Constructor ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```go pipeline := NewStreamingPipeline(WithCustomRenderer(myRenderer)) ``` ### Response #### Success Response (N/A) N/A #### Response Example N/A ``` ```APIDOC ## StreamingPipeline.StreamNodes ### Description Processes nodes in batches and streams the results, returning channels for nodes and errors. ### Method GET (Conceptual - returns streams) ### Endpoint N/A (Method on StreamingPipeline) ### Parameters #### Path Parameters None #### Query Parameters - **ctx** (context.Context) - Required - The context for the operation. - **source** (string) - Required - The source string to process. - **batchSize** (int) - Required - The number of nodes to process in each batch. #### Request Body None ### Request Example ```go nodesChan, errChan := sp.StreamNodes(context.Background(), "some_source_data", 100) for { select { case nodes, ok := <-nodesChan: if !ok { nodesChan = nil continue } // Process nodes case err, ok := <-errChan: if !ok { errChan = nil continue } // Handle error } if nodesChan == nil && errChan == nil { break } } ``` ### Response #### Success Response (200) - **<-chan []model.Node**: A channel that streams batches of nodes. - **<-chan error**: A channel that streams errors encountered during processing. #### Response Example N/A (Channels are returned, not a direct JSON response) ``` -------------------------------- ### Parse Proxy Nodes with Options in Go Source: https://pkg.go.dev/github.com/sixproxy/singgen/pkg/singgen?utm_source=chatgpt.com/index_utm_source=chatgpt.com Parses proxy nodes from a given source string. It accepts a context and optional configuration options to customize the parsing process. Returns a slice of Node and an error if parsing fails. ```go func ParseNodes(ctx context.Context, source string, opts ...Option) ([]Node, error) ``` -------------------------------- ### Define Common Errors for Configuration Generation (Go) Source: https://pkg.go.dev/github.com/sixproxy/singgen/pkg/singgen?utm_source=chatgpt.com/index_utm_source=chatgpt.com This snippet defines a set of common error variables used within the singgen package. These errors cover various failure scenarios during configuration generation, such as empty sources, invalid formats, parsing failures, and rendering issues. They are essential for robust error handling in applications using this package. ```Go var ( // ErrEmptySource is returned when no source URL or path is provided ErrEmptySource = errors.New("empty source URL or path") // ErrNoValidNodes is returned when no valid proxy nodes are found in the source ErrNoValidNodes = errors.New("no valid nodes found in source") // ErrUnsupportedFormat is returned when the output format is not supported ErrUnsupportedFormat = errors.New("unsupported output format") // ErrInvalidTemplate is returned when an invalid template version is specified ErrInvalidTemplate = errors.New("invalid template version") // ErrContextCanceled is returned when the operation is canceled via context ErrContextCanceled = errors.New("operation was canceled") // ErrInvalidPlatform is returned when an unsupported platform is specified ErrInvalidPlatform = errors.New("invalid platform") // ErrInvalidDNSServer is returned when an invalid DNS server address is provided ErrInvalidDNSServer = errors.New("invalid DNS server address") // ErrFetchFailed is returned when data fetching fails ErrFetchFailed = errors.New("failed to fetch data") // ErrParseFailed is returned when parsing fails ErrParseFailed = errors.New("failed to parse data") // ErrTransformFailed is returned when node transformation fails ErrTransformFailed = errors.New("failed to transform nodes") // ErrTemplateFailed is returned when template processing fails ErrTemplateFailed = errors.New("failed to process template") // ErrRenderFailed is returned when rendering the final configuration fails ErrRenderFailed = errors.New("failed to render configuration") ) ``` -------------------------------- ### Parse Only Pipeline Steps in Go Source: https://pkg.go.dev/github.com/sixproxy/singgen/pkg/singgen?utm_source=chatgpt.com/index_utm_source=chatgpt.com Executes the fetch and parse steps of the pipeline, returning the parsed nodes as a slice of model.Node. Errors during these steps are returned. ```go func (p *Pipeline) ParseOnly(ctx context.Context, source string) ([]model.Node, error) ``` -------------------------------- ### Transform Only Pipeline Steps in Go Source: https://pkg.go.dev/github.com/sixproxy/singgen/pkg/singgen?utm_source=chatgpt.com/index_utm_source=chatgpt.com Executes the fetch, parse, and transform steps of the pipeline, returning the transformed outbound rules as a slice. Errors are returned if any step fails. ```go func (p *Pipeline) TransformOnly(ctx context.Context, source string) ([]transformer.Outbound, error) ``` -------------------------------- ### Set Custom Fetcher Pipeline Option in Go Source: https://pkg.go.dev/github.com/sixproxy/singgen/pkg/singgen?utm_source=chatgpt.com/index_utm_source=chatgpt.com A PipelineOption that allows setting a custom fetcher for the pipeline. This enables replacing the default data fetching mechanism with a custom implementation. ```go func WithCustomFetcher(fetcher ContextFetcher) PipelineOption ``` -------------------------------- ### Set Client Subnet Option in Go Source: https://pkg.go.dev/github.com/sixproxy/singgen/pkg/singgen?utm_source=chatgpt.com/index_utm_source=chatgpt.com A functional option to set the client subnet for DNS queries during node generation. This allows specifying the network from which DNS requests appear to originate. ```go func WithClientSubnet(subnet string) Option ``` -------------------------------- ### Set Custom Parser Pipeline Option in Go Source: https://pkg.go.dev/github.com/sixproxy/singgen/pkg/singgen?utm_source=chatgpt.com/index_utm_source=chatgpt.com A PipelineOption that allows setting a custom parser for the pipeline. This enables replacing the default node parsing logic with a custom implementation. ```go func WithCustomParser(parser ContextParser) PipelineOption ``` -------------------------------- ### Streaming Pipeline Type (Go) Source: https://pkg.go.dev/github.com/sixproxy/singgen/pkg/singgen?utm_source=chatgpt.com/index_utm_source=chatgpt.com StreamingPipeline provides capabilities for processing large subscription files through streaming. It is designed for efficient handling of large data volumes. ```Go type StreamingPipeline struct { // contains filtered or unexported fields } ``` -------------------------------- ### Common Errors Source: https://pkg.go.dev/github.com/sixproxy/singgen/pkg/singgen?utm_source=chatgpt.com/index_utm_source=chatgpt.com A list of common errors that can occur during the configuration generation process. ```APIDOC ## Error Variables ### Description These variables represent common errors encountered during configuration generation. ### Errors - **ErrEmptySource**: Returned when no source URL or path is provided. - **ErrNoValidNodes**: Returned when no valid proxy nodes are found in the source. - **ErrUnsupportedFormat**: Returned when the output format is not supported. - **ErrInvalidTemplate**: Returned when an invalid template version is specified. - **ErrContextCanceled**: Returned when the operation is canceled via context. - **ErrInvalidPlatform**: Returned when an unsupported platform is specified. - **ErrInvalidDNSServer**: Returned when an invalid DNS server address is provided. - **ErrFetchFailed**: Returned when data fetching fails. - **ErrParseFailed**: Returned when parsing fails. - **ErrTransformFailed**: Returned when node transformation fails. - **ErrTemplateFailed**: Returned when template processing fails. - **ErrRenderFailed**: Returned when rendering the final configuration fails. ``` -------------------------------- ### Process Large Subscription Files with Streaming API Source: https://pkg.go.dev/github.com/sixproxy/singgen/pkg/singgen?utm_source=chatgpt.com/index_utm_source=chatgpt.com Utilizes the streaming API to efficiently process large subscription files. It returns channels for nodes and errors, enabling non-blocking processing of batches. ```go streaming := singgen.NewStreamingPipeline() nodesCh, errCh := streaming.StreamNodes(ctx, "large-subscription.txt", 100) for { select { case nodes, ok := <-nodesCh: if !ok { return } // Done // Process batch of nodes case err := <-errCh: // Handle error } } ``` -------------------------------- ### Define Pipeline Type in Go Source: https://pkg.go.dev/github.com/sixproxy/singgen/pkg/singgen?utm_source=chatgpt.com/index_utm_source=chatgpt.com Represents the low-level API for controlling the generation process. It allows injection of custom components and fine-grained control over each step. ```go type Pipeline struct { // contains filtered or unexported fields } ``` -------------------------------- ### Set Custom Transformer for Pipeline (Go) Source: https://pkg.go.dev/github.com/sixproxy/singgen/pkg/singgen?utm_source=chatgpt.com/index_utm_source=chatgpt.com WithCustomTransformer is used to set a custom transformer for the pipeline. This function takes a ContextTransformer and returns a PipelineOption. ```Go func WithCustomTransformer(transformer ContextTransformer) PipelineOption { // Implementation details omitted for brevity } ``` -------------------------------- ### Stream Nodes from Pipeline (Go) Source: https://pkg.go.dev/github.com/sixproxy/singgen/pkg/singgen?utm_source=chatgpt.com/index_utm_source=chatgpt.com StreamNodes processes nodes in batches and streams the results. It returns channels for nodes and errors, taking context, source string, and batch size as input. ```Go func (sp *StreamingPipeline) StreamNodes(ctx context.Context, source string, batchSize int) (<-chan []model.Node, <-chan error) { // Implementation details omitted for brevity } ``` -------------------------------- ### Define Pipeline Metadata Structure in Go Source: https://pkg.go.dev/github.com/sixproxy/singgen/pkg/singgen?utm_source=chatgpt.com/index_utm_source=chatgpt.com Defines the PipelineMetadata struct, which holds information about a pipeline execution, including source type, detected format, node and outbound counts, template version, and target platform. ```go type PipelineMetadata struct { SourceType string `json:"source_type"` DetectedFormat string `json:"detected_format"` NodesCount int `json:"nodes_count"` OutboundsCount int `json:"outbounds_count"` TemplateVersion string `json:"template_version"` Platform string `json:"platform"` } ``` -------------------------------- ### Set Logger Option in Go Source: https://pkg.go.dev/github.com/sixproxy/singgen/pkg/singgen?utm_source=chatgpt.com/index_utm_source=chatgpt.com A functional option to inject a custom logger instance (slog.Logger) into the generation process. This allows for centralized logging and debugging. ```go func WithLogger(logger *slog.Logger) Option ``` -------------------------------- ### Transform Only with Pipeline.TransformOnly Source: https://pkg.go.dev/github.com/sixproxy/singgen/pkg/singgen?utm_source=chatgpt.com/index_utm_source=chatgpt.com Transforms subscription data into the outbound proxy format without fetching or parsing. Returns a slice of transformer.Outbound objects. ```go pipeline := singgen.NewPipeline(opts ...PipelineOption) outbounds, err := pipeline.TransformOnly(ctx, source) ``` -------------------------------- ### Pipeline Result Structure (Go) Source: https://pkg.go.dev/github.com/sixproxy/singgen/pkg/singgen?utm_source=chatgpt.com/index_utm_source=chatgpt.com PipelineResult holds the complete outcome of a pipeline execution. It includes configuration, nodes, outbounds, and metadata. ```Go type PipelineResult struct { Config *config.Config `json:"config"` Nodes []model.Node `json:"nodes"` Outbounds []transformer.Outbound `json:"outbounds"` Metadata PipelineMetadata `json:"metadata"` } ``` -------------------------------- ### Parse Nodes from Source Data (Go) Source: https://pkg.go.dev/github.com/sixproxy/singgen/pkg/singgen?utm_source=chatgpt.com/index_utm_source=chatgpt.com The ParseNodes method of the Generator struct is responsible for extracting and parsing proxy nodes from a given source string. It utilizes the configured fetcher and parser to process the source data and returns a slice of Node objects. This method provides a way to specifically work with the parsed node data before full configuration generation. ```Go func (g *Generator) ParseNodes(ctx context.Context, source string) ([]Node, error) ``` -------------------------------- ### Set HTTP Timeout Option in Go Source: https://pkg.go.dev/github.com/sixproxy/singgen/pkg/singgen?utm_source=chatgpt.com/index_utm_source=chatgpt.com A functional option to configure the timeout duration for HTTP requests made during the generation process. This helps prevent indefinitely hanging requests. ```go func WithHTTPTimeout(timeout time.Duration) Option ``` -------------------------------- ### Set External Controller Address Option in Go Source: https://pkg.go.dev/github.com/sixproxy/singgen/pkg/singgen?utm_source=chatgpt.com/index_utm_source=chatgpt.com A functional option to set the address of an external controller, typically used for interacting with the Clash API. This is useful for remote management or integration. ```go func WithExternalController(addr string) Option ``` -------------------------------- ### Define Pipeline Option Type in Go Source: https://pkg.go.dev/github.com/sixproxy/singgen/pkg/singgen?utm_source=chatgpt.com/index_utm_source=chatgpt.com Defines the PipelineOption type, a function type used for configuring a Pipeline instance. This enables the functional options pattern for pipeline customization. ```go type PipelineOption func(*Pipeline) ``` -------------------------------- ### Parse Only with Pipeline.ParseOnly Source: https://pkg.go.dev/github.com/sixproxy/singgen/pkg/singgen?utm_source=chatgpt.com/index_utm_source=chatgpt.com Parses subscription data to extract node information without fetching or transforming. Returns a slice of Node objects. ```go pipeline := singgen.NewPipeline(opts ...PipelineOption) nodes, err := pipeline.ParseOnly(ctx, source) ``` -------------------------------- ### Parse Nodes with ParseNodes Function Source: https://pkg.go.dev/github.com/sixproxy/singgen/pkg/singgen?utm_source=chatgpt.com/index_utm_source=chatgpt.com Parses subscription data to extract node information. This function can be used independently for node parsing tasks. ```go nodes, err := singgen.ParseNodes(ctx, source, opts ...Option) ``` -------------------------------- ### PipelineResult Structure Source: https://pkg.go.dev/github.com/sixproxy/singgen/pkg/singgen?utm_source=chatgpt.com/index_utm_source=chatgpt.com Defines the structure of the result returned after a pipeline execution, including configuration, nodes, outbounds, and metadata. ```APIDOC ## PipelineResult Structure ### Description Contains the complete result of a pipeline execution. ### Method N/A (This is a type definition) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example N/A ### Response #### Success Response (N/A) N/A #### Response Example ```json { "config": { ... }, "nodes": [ ... ], "outbounds": [ ... ], "metadata": { ... } } ``` ``` -------------------------------- ### Enable/Disable Emoji Removal Option in Go Source: https://pkg.go.dev/github.com/sixproxy/singgen/pkg/singgen?utm_source=chatgpt.com/index_utm_source=chatgpt.com A functional option to control whether emojis are removed from node tags during generation. This allows customization of tag content. ```go func WithEmojiRemoval(remove bool) Option ``` -------------------------------- ### Define Node Type in Go Source: https://pkg.go.dev/github.com/sixproxy/singgen/pkg/singgen?utm_source=chatgpt.com/index_utm_source=chatgpt.com Defines the Node type, which represents a parsed proxy node. It is an alias for model.Node, indicating it's used for structured data representation within the package. ```go type Node = model.Node ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.