### Create New App Instance Source: https://github.com/gui-for-cores/gui.for.singbox/blob/main/_autodocs/api-reference/app.md Use `NewApp` to create a basic application instance with an empty menu. This is useful for starting with a minimal setup. ```go func NewApp() *App { return &App{ AppMenu: menu.NewMenu(), } } ``` -------------------------------- ### Start HTTPS Server with Options Source: https://github.com/gui-for-cores/gui.for.singbox/blob/main/_autodocs/api-reference/server.md Starts an HTTPS server using provided certificate and key files, along with static file serving configuration. Both `Cert` and `Key` paths must be valid for HTTPS to be enabled; otherwise, it defaults to HTTP. ```go result := app.StartServer( "0.0.0.0:8443", "https-server", ServerOptions{ Cert: "data/cert.pem", Key: "data/key.pem", StaticPath: "data/www", StaticRoute: "/", }, ) ``` -------------------------------- ### Start HTTP Server with Options Source: https://github.com/gui-for-cores/gui.for.singbox/blob/main/_autodocs/api-reference/server.md Starts an HTTP server with specified address, ID, and configuration options including static file serving and uploads. Ensure the `ServerOptions` are correctly populated for desired features. ```go result := app.StartServer( "127.0.0.1:8080", "my-server", ServerOptions{ StaticPath: "data/www", StaticRoute: "/static/", UploadPath: "data/uploads", UploadRoute: "/upload", MaxUploadSize: 100 * 1024 * 1024, // 100MB }, ) ``` -------------------------------- ### Example AppConfig YAML Source: https://github.com/gui-for-cores/gui.for.singbox/blob/main/_autodocs/types.md An example of how to configure the application settings in the `data/user.yaml` file. This demonstrates the expected format and values for various configuration fields. ```yaml windowStartState: 0 webviewGpuPolicy: 0 contentProtection: true width: 1024 height: 768 multipleInstance: false rollingRelease: true ``` -------------------------------- ### Example Application Configuration Source: https://github.com/gui-for-cores/gui.for.singbox/blob/main/_autodocs/configuration.md An example of a complete configuration file for the GUI.for.SingBox application, including settings for window appearance, Windows-specific features, instance behavior, and caching. ```yaml # Window appearance windowStartState: 0 width: 1280 height: 800 # Windows-specific settings webviewGpuPolicy: 0 contentProtection: true # Instance behavior multipleInstance: false # Caching rollingRelease: true ``` -------------------------------- ### StartServer() Source: https://github.com/gui-for-cores/gui.for.singbox/blob/main/_autodocs/api-reference/frontend.md Starts an HTTP server at the specified address with a custom request handler and optional server configurations. ```APIDOC ## StartServer() ### Description Starts an HTTP server at the specified address with a custom request handler and optional server configurations. ### Method Signature ```typescript export const StartServer: (address: string, id: string, handler: (req: Request, res: { end: (status, headers, body, options) => void }) => Promise, options?: ServerOptions) => Promise<{ close: () => Promise }> ``` ### Example ```typescript const server = await StartServer( '127.0.0.1:8080', 'my-server', async (req, res) => { if (req.method === 'GET' && req.url === '/') { res.end(200, {}, 'Hello World', { mode: 'Text' }) } else { res.end(404, {}, 'Not Found', { mode: 'Text' }) } }, { StaticPath: 'data/www', StaticRoute: '/static/', } ) // Close server await server.close() ``` ``` -------------------------------- ### Install pnpm Source: https://github.com/gui-for-cores/gui.for.singbox/blob/main/README.md Installs pnpm globally using npm. This is a prerequisite for building the frontend. ```bash npm i -g pnpm ``` -------------------------------- ### Build GUI for SingBox Source: https://github.com/gui-for-cores/gui.for.singbox/blob/main/README.md Clones the repository, installs frontend dependencies, builds the frontend, and then builds the Wails application. ```bash git clone https://github.com/GUI-for-Cores/GUI.for.SingBox.git cd GUI.for.SingBox/frontend pnpm install --frozen-lockfile && pnpm build cd .. wails build ``` -------------------------------- ### Build Frontend and App Source: https://github.com/gui-for-cores/gui.for.singbox/blob/main/_autodocs/index.md Steps to build the frontend assets and then package the entire application using Wails CLI. Ensure all prerequisites like Go, Node.js, and pnpm are installed. ```bash # Build frontend cd frontend pnpm install --frozen-lockfile && pnpm build cd .. # Build and package app wails build ``` -------------------------------- ### Example Usage of KillProcess Source: https://github.com/gui-for-cores/gui.for.singbox/blob/main/_autodocs/api-reference/exec.md Demonstrates how to call the KillProcess function with a process ID and timeout, and check the result. Use this to gracefully terminate a running process. ```go result := app.KillProcess(1234, 10) // 10 second timeout if result.Flag { println("Process terminated") } ``` -------------------------------- ### Start HTTP Server Source: https://github.com/gui-for-cores/gui.for.singbox/blob/main/_autodocs/api-reference/frontend.md Use StartServer to launch an HTTP server with a custom request handler and optional server configurations like static file serving. ```typescript export const StartServer: ( address: string, id: string, handler: ( req: Request, res: { end: (status, headers, body, options) => void } ) => Promise, options?: ServerOptions, ) => Promise<{ close: () => Promise }> ``` ```typescript const server = await StartServer( '127.0.0.1:8080', 'my-server', async (req, res) => { if (req.method === 'GET' && req.url === '/') { res.end(200, {}, 'Hello World', { mode: 'Text' }) } else { res.end(404, {}, 'Not Found', { mode: 'Text' }) } }, { StaticPath: 'data/www', StaticRoute: '/static/', } ) // Close server await server.close() ``` -------------------------------- ### StartServer Source: https://github.com/gui-for-cores/gui.for.singbox/blob/main/_autodocs/api-reference/server.md Starts an HTTP(S) server with static files, uploads, and custom request handling. It binds to a specified address and uses a unique server ID for event handling. The server supports various features configurable via `ServerOptions`. ```APIDOC ## StartServer ### Description Starts an HTTP(S) server with static files, uploads, and custom request handling. ### Method Signature ```go func (a *App) StartServer(address string, serverID string, options ServerOptions) FlagResult ``` ### Parameters #### Path Parameters - **address** (string) - Required - Bind address (e.g., "127.0.0.1:8080", "[::]:8080") - **serverID** (string) - Required - Unique server identifier #### Request Body - **options** (ServerOptions) - Optional - Server configuration - **StaticPath** (string) - Path to serve static files from. - **StaticRoute** (string) - Route prefix for static files. - **UploadPath** (string) - Path to save uploaded files. - **UploadRoute** (string) - Route for handling file uploads. - **MaxUploadSize** (int64) - Maximum size for uploads (default: 50MB). - **Cert** (string) - Path to the TLS certificate file (PEM format). - **Key** (string) - Path to the TLS private key file (PEM format). ### Server Features - **Static File Serving:** Enabled when `StaticPath` and `StaticRoute` are set. Routes matching `StaticRoute` serve static files. `StaticHeaders` are applied to all responses. OPTIONS requests return 204 No Content. - **File Upload (Multipart/Form-Data):** Enabled when `UploadPath` and `UploadRoute` are set. POST/PUT requests to `UploadRoute` save files. Parses multipart form or raw file upload. `X-Filename` header is required for raw uploads. `MaxUploadSize` defaults to 50MB. - **Custom Request Handling:** All requests emit Wails events with the name `serverID`. The frontend handler responds with status, headers, and body. Each request has a 60-second timeout. - **TLS/HTTPS:** Enabled by setting `Cert` and `Key`. Both files are required; if either is missing, HTTP is used. `Cert` must be an X.509 certificate in PEM format, and `Key` must be a private key in PEM format. ### Error Handling - **500 Internal Server Error:** If the upload directory creation fails. - **400 Bad Request:** For invalid multipart data. - **405 Method Not Allowed:** For unsupported HTTP methods. - **20MB max request body size** ### Throws/Errors - **"server already exists"**: If `serverID` is already in use. - **"Failed to bind address"**: If the port is in use or the address is invalid. - **"Failed to load TLS cert"**: If the `Cert`/`Key` files are invalid or unreadable. ### Request Example ```go result := app.StartServer( "127.0.0.1:8080", "my-server", ServerOptions{ StaticPath: "data/www", StaticRoute: "/static/", UploadPath: "data/uploads", UploadRoute: "/upload", MaxUploadSize: 100 * 1024 * 1024, // 100MB }, ) // Or with HTTPS result := app.StartServer( "0.0.0.0:8443", "https-server", ServerOptions{ Cert: "data/cert.pem", Key: "data/key.pem", StaticPath: "data/www", StaticRoute: "/", }, ) ``` ### Custom Request Handler (Frontend) ```javascript // Listen for requests runtime.EventsOn("my-server", async (requestID, method, path, headers, body) => { // Handle request const response = { status: 200, headers: {}, body: "OK" }; // Send response runtime.EventsEmit(requestID, response.status, response.headers, response.body, {}) }) ``` ``` -------------------------------- ### SendTCP Example Source: https://github.com/gui-for-cores/gui.for.singbox/blob/main/_autodocs/api-reference/network.md Sends data to a TCP server and retrieves the response. Use 'Text' mode for UTF-8 or 'Binary' for base64 encoding. Timeout is in seconds. ```go result := app.SendTCP("example.com:8080", "Hello", NetOptions{Mode: "Text", Timeout: 5}) ``` -------------------------------- ### ExecOptions Struct Definition Source: https://github.com/gui-for-cores/gui.for.singbox/blob/main/_autodocs/types.md Defines configuration options for executing external processes. Use this when starting or managing background processes. ```go type ExecOptions struct { PidFile string LogFile string StopOutputKeyword string WorkingDirectory string Convert bool Env map[string]string } ``` -------------------------------- ### Execute Command with FlagResult Source: https://github.com/gui-for-cores/gui.for.singbox/blob/main/_autodocs/types.md Example of executing a command and checking the FlagResult. The 'Flag' field determines whether to process output or an error. ```go result := app.Exec("ls", []string{"-", "-"}, ExecOptions{}) if result.Flag { println("Output:", result.Data) } else { println("Error:", result.Data) } ``` -------------------------------- ### HTTP Server Methods - Go Source: https://github.com/gui-for-cores/gui.for.singbox/blob/main/_autodocs/exported-symbols.md APIs for managing HTTP servers. Allows starting, stopping, and listing active servers by ID. ```go func (a *App) StartServer(address string, serverID string, options ServerOptions) FlagResult func (a *App) StopServer(id string) FlagResult func (a *App) ListServer() FlagResult ``` -------------------------------- ### SendUDP Example Source: https://github.com/gui-for-cores/gui.for.singbox/blob/main/_autodocs/api-reference/network.md Sends a UDP datagram. This is a fire-and-forget operation. Use 'Binary' mode for base64 encoding. ```go app.SendUDP("192.168.1.1:53", "dns_query_data", NetOptions{Mode: "Binary"}) ``` -------------------------------- ### OpenMMDB Usage Example Source: https://github.com/gui-for-cores/gui.for.singbox/blob/main/_autodocs/api-reference/mmdb.md Demonstrates how to use the OpenMMDB function to open a GeoIP database file. It checks the returned FlagResult for success and prints an error message if opening fails. ```go result := app.OpenMMDB("data/GeoLite2-City.mmdb", "geo-service-1") if !result.Flag { println("Failed to open:", result.Data) } ``` -------------------------------- ### Get Network Interfaces Source: https://github.com/gui-for-cores/gui.for.singbox/blob/main/_autodocs/api-reference/app.md Lists all available network interfaces on the system. Returns a FlagResult where Data contains interface names separated by '|' if successful. ```Go func (a *App) GetInterfaces() FlagResult ``` ```Go result := app.GetInterfaces() if result.Flag { names := strings.Split(result.Data, "|") for _, name := range names { println(name) // e.g., "eth0", "wlan0" } } ``` -------------------------------- ### Server Module Functions Source: https://github.com/gui-for-cores/gui.for.singbox/blob/main/_autodocs/exported-symbols.md Functions for managing servers. Use these to start, stop, and list active servers. ```typescript export const StartServer: (address, id, handler, options?) => Promise<{ close }> export const StopServer: (serverID) => Promise export const ListServer: () => Promise ``` -------------------------------- ### HTTP Server Entry Structure Source: https://github.com/gui-for-cores/gui.for.singbox/blob/main/_autodocs/api-reference/server.md Defines the internal structure for managing a single HTTP server instance. This is used by server start and stop functions. ```Go type serverEntry struct { server *http.Server } ``` -------------------------------- ### MMDB Lifecycle Example Source: https://github.com/gui-for-cores/gui.for.singbox/blob/main/_autodocs/api-reference/mmdb.md Illustrates the reference counting mechanism for MMDB readers. Multiple services can share a reader, and the database is only closed when all references are released. This ensures thread safety using RWMutex for open, close, and query operations. ```text Service A: OpenMMDB("city.mmdb", "service-a") // Loads file, refs["service-a"] = true Service B: OpenMMDB("city.mmdb", "service-b") // Same reader, refs["service-b"] = true Service A: QueryMMDB(...) + QueryMMDB(...) // Uses shared reader Service B: QueryMMDB(...) // Uses shared reader Service A: CloseMMDB("city.mmdb", "service-a") // Removes "service-a" ref Service B: CloseMMDB("city.mmdb", "service-b") // Removes "service-b" ref, closes reader ``` -------------------------------- ### Get Process Information by PID Source: https://github.com/gui-for-cores/gui.for.singbox/blob/main/_autodocs/api-reference/exec.md Retrieves the process name, executable path, or command line for a given process ID. Returns FlagResult.Flag=false if the process is not found or all queries fail. ```go func (a *App) ProcessInfo(pid int32) FlagResult ``` ```go result := app.ProcessInfo(1234) if result.Flag { println("Process name:", result.Data) // e.g., "python3" } ``` -------------------------------- ### Get Environment Variable or App Metadata Source: https://github.com/gui-for-cores/gui.for.singbox/blob/main/_autodocs/api-reference/app.md Retrieves a specific environment variable by key, or application metadata when the key is empty. The return type is 'any' and requires a type assertion. ```Go func (a *App) GetEnv(key string) any ``` ```Go // Get specific env var path := app.GetEnv("PATH") // string // Get app metadata env := app.GetEnv("").(EnvResult) println(env.AppName, env.AppVersion) ``` -------------------------------- ### Get Process Memory Usage by PID Source: https://github.com/gui-for-cores/gui.for.singbox/blob/main/_autodocs/api-reference/exec.md Gets the RSS (resident set size) memory usage for a process in bytes. On macOS, it falls back to `ps -o rss=` if MemoryInfo fails and converts KB to bytes. The result is returned as a string. ```go func (a *App) ProcessMemory(pid int32) FlagResult ``` ```go result := app.ProcessMemory(1234) if result.Flag { bytes, _ := strconv.ParseUint(result.Data, 10, 64) mb := bytes / (1024 * 1024) println("Memory:", mb, "MB") } ``` -------------------------------- ### MakeDir: Create Directory Recursively Source: https://github.com/gui-for-cores/gui.for.singbox/blob/main/_autodocs/api-reference/io.md Creates a directory and all parent directories. Equivalent to `mkdir -p`. Does not fail if directory exists. ```go func (a *App) MakeDir(path string) FlagResult ``` ```go app.MakeDir("data/cache/temp") ``` -------------------------------- ### Get Process Information Source: https://github.com/gui-for-cores/gui.for.singbox/blob/main/_autodocs/api-reference/frontend.md ProcessInfo retrieves the name of a running process using its process ID. ```typescript export const ProcessInfo: (pid: number) => Promise ``` -------------------------------- ### Get File SHA256 Hash Source: https://github.com/gui-for-cores/gui.for.singbox/blob/main/_autodocs/api-reference/frontend.md Calculates and returns the SHA256 hash of a file as a hexadecimal string. ```typescript export const FileSHA256: (path: string) => Promise ``` -------------------------------- ### Check for First Startup Source: https://github.com/gui-for-cores/gui.for.singbox/blob/main/_autodocs/api-reference/app.md Use this function to execute initialization logic only on the very first launch of the application in a session. Subsequent calls will return false. ```go if app.IsStartup() { // Initialize app data, settings, etc. } ``` -------------------------------- ### Initialize Complete App with Embedded Resources Source: https://github.com/gui-for-cores/gui.for.singbox/blob/main/_autodocs/api-reference/app.md Use `CreateApp` to initialize a fully functional application. It requires embedded filesystem resources for frontend assets and handles various initialization steps including configuration loading and runtime extraction. ```go //go:embed all:frontend/dist var assets embed.FS app := bridge.CreateApp(assets) ``` -------------------------------- ### ProcessMemory Source: https://github.com/gui-for-cores/gui.for.singbox/blob/main/_autodocs/api-reference/exec.md Gets the Resident Set Size (RSS) memory usage for a given process ID in bytes. ```APIDOC ## ProcessMemory(pid int32) ### Description Gets RSS (resident set size) memory usage for a process. ### Parameters #### Path Parameters - **pid** (int32) - Required - Process ID ### Returns `FlagResult` — memory in bytes as string ### Platform Behavior - **Linux/Windows:** Uses gopsutil MemoryInfo - **macOS:** Fallback to `ps -o rss=` if MemoryInfo fails; converts KB to bytes ### Example ```go result := app.ProcessMemory(1234) if result.Flag { bytes, _ := strconv.ParseUint(result.Data, 10, 64) mb := bytes / (1024 * 1024) println("Memory:", mb, "MB") } ``` ``` -------------------------------- ### NewApp() Source: https://github.com/gui-for-cores/gui.for.singbox/blob/main/_autodocs/api-reference/app.md Creates a new App instance with an empty menu. This is a basic constructor for an App. ```APIDOC ## NewApp() ### Description Creates a new App instance with an empty menu. ### Returns - *App — new application instance ``` -------------------------------- ### Get Process Memory Usage Source: https://github.com/gui-for-cores/gui.for.singbox/blob/main/_autodocs/api-reference/frontend.md ProcessMemory returns the memory usage of a process in bytes, identified by its process ID. ```typescript export const ProcessMemory: (pid: number) => Promise ``` -------------------------------- ### Exported Constructor Functions - Go Source: https://github.com/gui-for-cores/gui.for.singbox/blob/main/_autodocs/exported-symbols.md Functions for creating instances of the App and related components. Includes creating a new App instance or an App instance with embedded file system support, and setting up tray functionality. ```go func NewApp() *App func CreateApp(fs embed.FS) *App func CreateTray(a *App, icon []byte) (trayStart, trayEnd func()) ``` -------------------------------- ### MakeDir Source: https://github.com/gui-for-cores/gui.for.singbox/blob/main/_autodocs/api-reference/io.md Creates a directory and all parent directories. Equivalent to `mkdir -p`. Does not fail if directory exists. ```APIDOC ## MakeDir(path string) ### Description Creates a directory and all parent directories. ### Method ```go func (a *App) MakeDir(path string) FlagResult ``` ### Parameters #### Path Parameters - **path** (string) - Required - Directory path ### Returns `FlagResult` — success flag ### Example ```go app.MakeDir("data/cache/temp") ``` ``` -------------------------------- ### Define AppConfig Structure Source: https://github.com/gui-for-cores/gui.for.singbox/blob/main/_autodocs/types.md Defines the application configuration loaded from YAML. Fields include window state, GPU policy, content protection, dimensions, instance management, and release strategy. The `StartHidden` field is for runtime use only and not persisted in YAML. ```go type AppConfig struct { WindowStartState int `yaml:"windowStartState"` WebviewGpuPolicy int `yaml:"webviewGpuPolicy"` ContentProtection bool `yaml:"contentProtection"` Width int `yaml:"width"` Height int `yaml:"height"` MultipleInstance bool `yaml:"multipleInstance"` RollingRelease bool `yaml:"rollingRelease" default:"true"` StartHidden bool } ``` -------------------------------- ### Get System Proxy Configuration Source: https://github.com/gui-for-cores/gui.for.singbox/blob/main/_autodocs/api-reference/frontend.md Retrieves the current system-wide proxy URL. This function may throw an error if the proxy information cannot be fetched. ```typescript const proxy = await GetSystemProxy() // "http://proxy.example.com:8080" ``` -------------------------------- ### Get System Proxy Bypass List Source: https://github.com/gui-for-cores/gui.for.singbox/blob/main/_autodocs/api-reference/app.md Retrieves the current bypass list for the system proxy. The returned data is a comma-separated string of hosts. ```go result := app.GetSystemProxyBypass() if result.Flag { bypass := strings.Split(result.Data, ",") for _, host := range bypass { println("Bypassed:", host) } } ``` -------------------------------- ### App Struct Methods - Go Source: https://github.com/gui-for-cores/gui.for.singbox/blob/main/_autodocs/exported-symbols.md Methods for interacting with the application lifecycle and environment. Includes checking startup status, exiting, restarting, and retrieving environment variables or network interfaces. ```go type App struct { ... } func (a *App) IsStartup() bool func (a *App) ExitApp() func (a *App) RestartApp() FlagResult func (a *App) GetEnv(key string) any func (a *App) GetInterfaces() FlagResult func (a *App) ShowMainWindow() ``` -------------------------------- ### CreateApp(fs embed.FS) Source: https://github.com/gui-for-cores/gui.for.singbox/blob/main/_autodocs/api-reference/app.md Initializes a complete application with embedded resources and configuration. This function handles several initialization steps including setting paths, detecting launch environment, and loading configuration. ```APIDOC ## CreateApp(fs embed.FS) ### Description Initializes a complete application with embedded resources and configuration. ### Parameters #### Path Parameters - fs (embed.FS) - Required - Embedded frontend build artifacts ### Initialization Steps 1. Sets executable path and app name from `os.Executable()` 2. Detects if launched from task scheduler (checks "tasksch" arg) 3. Checks for elevated privileges 4. Handles macOS symlink for app data directory 5. Extracts WebView2 runtime on Windows if needed 6. Extracts embedded icon/image resources 7. Loads user configuration from `data/user.yaml` ### Request Example ```go //go:embed all:frontend/dist var assets embed.FS app := bridge.CreateApp(assets) ``` ### Returns - *App — fully initialized application ``` -------------------------------- ### Create HTTP Client with Request Options Source: https://github.com/gui-for-cores/gui.for.singbox/blob/main/_autodocs/api-reference/network.md Creates an HTTP client with proxy, TLS, and timeout configurations. It caches transport objects by proxy URL and insecure flag to reuse connections. Returns the configured client, a context for cancellation, and the cancel function. ```go func withRequestOptionsClient(options RequestOptions) (*http.Client, context.Context, context.CancelFunc) ``` -------------------------------- ### Restart Application Source: https://github.com/gui-for-cores/gui.for.singbox/blob/main/_autodocs/api-reference/app.md Restarts the application by launching a new instance and closing the current one. Check the returned FlagResult for success or failure, especially if the executable cannot be found or spawned. ```go result := app.RestartApp() if !result.Flag { println("Restart failed:", result.Data) } ``` -------------------------------- ### MakeDir Source: https://github.com/gui-for-cores/gui.for.singbox/blob/main/_autodocs/api-reference/frontend.md Creates a directory, including any necessary parent directories. ```APIDOC ## MakeDir() ### Description Creates a directory and its parent directories if they do not exist. ### Method ```typescript MakeDir: (path: string) => Promise ``` ### Parameters #### Path Parameters - **path** (string) - Required - The path of the directory to create. ``` -------------------------------- ### getDarwinProcessRSS Source: https://github.com/gui-for-cores/gui.for.singbox/blob/main/_autodocs/api-reference/exec.md A fallback function for macOS to get the Resident Set Size (RSS) of a process using the 'ps' command. It returns the memory usage in bytes. ```APIDOC ## getDarwinProcessRSS(pid int32) ### Description Fallback for macOS process memory using `ps` command. ### Parameters #### Path Parameters - **pid** (int32) - Required - The process ID. ### Returns - `uint64` - Memory in bytes (KB converted to bytes). - `error` - An error if one occurred. ### Source `bridge/exec.go:279` ``` -------------------------------- ### requestTransport Source: https://github.com/gui-for-cores/gui.for.singbox/blob/main/_autodocs/api-reference/network.md Gets or creates a cached HTTP transport. The caching strategy keys transports by proxy URL and insecure flag to ensure connection reuse. ```APIDOC ## requestTransport(options RequestOptions) ### Description Gets or creates cached HTTP transport. ### Caching Strategy Keyed by (proxy URL, insecure flag) to reuse connections. ### Signature ```go func requestTransport(options RequestOptions) *http.Transport ``` ``` -------------------------------- ### Open URI with Default Application Source: https://github.com/gui-for-cores/gui.for.singbox/blob/main/_autodocs/api-reference/io.md Opens a given URI (like a URL or mailto link) using the system's default application for that URI type. ```go app.OpenURI("https://example.com") ``` ```go app.OpenURI("mailto:user@example.com") ``` -------------------------------- ### Get System Proxy Bypass List Source: https://github.com/gui-for-cores/gui.for.singbox/blob/main/_autodocs/api-reference/frontend.md Retrieves the current list of hosts and domains that are bypassed by the system proxy settings. The list is returned as a comma-separated string. ```typescript export const GetSystemProxyBypass: () => Promise ``` -------------------------------- ### Serve Static Files with Custom Headers Source: https://github.com/gui-for-cores/gui.for.singbox/blob/main/_autodocs/api-reference/server.md Serves static files while applying custom headers to the response. It also handles OPTIONS requests and delegates the actual file serving to http.FileServer. ```Go func handleFileDownload(w http.ResponseWriter, r *http.Request, fs http.Handler, headers map[string]string) ``` -------------------------------- ### Tray Methods - Go Source: https://github.com/gui-for-cores/gui.for.singbox/blob/main/_autodocs/exported-symbols.md Methods for updating the application's system tray icon and context menus. Allows dynamic modification of tray content and menu items. ```go func (a *App) UpdateTray(tray TrayContent) func (a *App) UpdateTrayMenus(menus []MenuItem) func (a *App) UpdateTrayAndMenus(tray TrayContent, menus []MenuItem) ``` -------------------------------- ### Create Directory Source: https://github.com/gui-for-cores/gui.for.singbox/blob/main/_autodocs/api-reference/frontend.md Creates a directory, including any necessary parent directories. ```typescript export const MakeDir: (path: string) => Promise ``` -------------------------------- ### File I/O Methods - Go Source: https://github.com/gui-for-cores/gui.for.singbox/blob/main/_autodocs/exported-symbols.md Utilities for performing file operations such as reading, writing, moving, deleting, copying, and directory manipulation. Also includes functions for checking file existence, calculating SHA256 hashes, and opening files or URIs. ```go func (a *App) WriteFile(path string, content string, options IOOptions) FlagResult func (a *App) ReadFile(path string, options IOOptions) FlagResult func (a *App) MoveFile(source string, target string) FlagResult func (a *App) RemoveFile(path string) FlagResult func (a *App) CopyFile(src string, dst string) FlagResult func (a *App) MakeDir(path string) FlagResult func (a *App) ReadDir(path string) FlagResult func (a *App) FileExists(path string) FlagResult func (a *App) FileSHA256(path string) FlagResult func (a *App) OpenDir(path string) FlagResult func (a *App) OpenURI(uri string) FlagResult func (a *App) AbsolutePath(path string) FlagResult ``` -------------------------------- ### Relative Path Resolution in Go Source: https://github.com/gui-for-cores/gui.for.singbox/blob/main/_autodocs/configuration.md Demonstrates how relative paths are automatically resolved from the application's base directory for file operations and directory creation. ```go app.ReadFile("data/config.json", IOOptions{}) // Becomes: {base_path}/data/config.json app.MakeDir("data/logs") // Becomes: {base_path}/data/logs ``` -------------------------------- ### readFileRange Go Function Signature Source: https://github.com/gui-for-cores/gui.for.singbox/blob/main/_autodocs/api-reference/exec.md Defines the signature for readFileRange, used to read a specific chunk of a file starting from a given offset. It returns the data, the next offset, and any error encountered. ```go func readFileRange(path string, offset int64) ([]byte, int64, error) ``` -------------------------------- ### Get Environment Variable or App Metadata Source: https://github.com/gui-for-cores/gui.for.singbox/blob/main/_autodocs/api-reference/frontend.md Retrieves a specific environment variable by its key, or all application environment metadata if no key is provided. The return type depends on whether a key is specified. ```typescript // Single env var const path = await GetEnv('PATH') // string // All metadata const env = await GetEnv() // AppEnv console.log(env.appName, env.appVersion, env.os) ``` -------------------------------- ### Show Application Main Window Source: https://github.com/gui-for-cores/gui.for.singbox/blob/main/_autodocs/api-reference/app.md Makes the application window visible. This function is platform-specific and relies on the Wails runtime. ```go func (a *App) ShowMainWindow() ``` -------------------------------- ### App Module Functions Source: https://github.com/gui-for-cores/gui.for.singbox/blob/main/_autodocs/exported-symbols.md Functions for controlling the application lifecycle and UI. Use these for restarting, exiting, showing the main window, checking startup status, getting environment variables, and managing system proxy settings. ```typescript export const RestartApp: () => Promise export const ExitApp: () => Promise export const ShowMainWindow: () => Promise export const IsStartup: () => Promise export const GetEnv: (key?: T) => Promise<...> export const GetSystemProxy: () => Promise export const SetSystemProxy: (enable, server, proxyType?, bypass?, services?) => Promise export const GetSystemProxyBypass: () => Promise export const SetSystemDNS: (servers, services?) => Promise export const GetInterfaces: () => Promise export const Notify: (title, body) => Promise export const UpdateTray: (tray) => Promise export const UpdateTrayMenus: (menus) => Promise export const UpdateTrayAndMenus: (tray, menus) => Promise ``` -------------------------------- ### GetInterfaces() Source: https://github.com/gui-for-cores/gui.for.singbox/blob/main/_autodocs/api-reference/frontend.md Lists the names of available network interfaces on the system. ```APIDOC ## GetInterfaces() ### Description Lists network interface names. ### Method `async` ### Endpoint `bridge/app.ts` ### Parameters None ### Response #### Success Response `Promise` - An array of network interface names (e.g., ["eth0", "wlan0"]). ### Example ```typescript const interfaces = await GetInterfaces() // ["eth0", "wlan0"] ``` ``` -------------------------------- ### Get or Create Cached HTTP Transport Source: https://github.com/gui-for-cores/gui.for.singbox/blob/main/_autodocs/api-reference/network.md Retrieves an HTTP transport object from a cache or creates a new one if it doesn't exist. The cache is keyed by the proxy URL and an insecure flag to efficiently reuse connections. ```go func requestTransport(options RequestOptions) *http.Transport ``` -------------------------------- ### GetInterfaces Source: https://github.com/gui-for-cores/gui.for.singbox/blob/main/_autodocs/api-reference/app.md Lists all available network interfaces on the system. Returns their names as a pipe-delimited string. ```APIDOC ## GetInterfaces() ### Description Queries the system for all network interfaces and returns their names separated by "|". ### Returns `FlagResult` — pipe-delimited string of interface names on success ### Example ```go result := app.GetInterfaces() if result.Flag { names := strings.Split(result.Data, "|") for _, name := range names { println(name) // e.g., "eth0", "wlan0" } } ``` ``` -------------------------------- ### readFileRange Source: https://github.com/gui-for-cores/gui.for.singbox/blob/main/_autodocs/api-reference/exec.md Reads a chunk of a file starting at a specified offset. It returns the data read, the next offset to read from, and any error encountered. The offset is clamped to the file size, and an empty slice is returned if the offset is already at the end of the file. ```APIDOC ## readFileRange(path string, offset int64) ### Description Reads a chunk of a file starting at offset. ### Parameters #### Path Parameters - **path** (string) - Required - The path to the file. - **offset** (int64) - Required - The starting offset in bytes to read from. ### Returns - `[]byte` - The data read from the file. - `int64` - The next offset to read from. - `error` - An error if one occurred during reading. ### Behavior - Clamps offset to file size - Returns empty if offset == file size - Returns actual bytes read (may be < requested) ### Source `bridge/exec.go:402` ``` -------------------------------- ### ExecOptions Source: https://github.com/gui-for-cores/gui.for.singbox/blob/main/_autodocs/types.md Configuration for process execution. Used by Exec() and ExecBackground(). ```APIDOC ## ExecOptions ### Description Configuration for process execution. ### Fields - **PidFile** (string) - Write process ID to this file path - **LogFile** (string) - Redirect stdout/stderr to file instead of events - **StopOutputKeyword** (string) - Stop emitting output lines when this text appears - **WorkingDirectory** (string) - Process working directory - **Convert** (bool) - Decode GB18030 Chinese encoding from output - **Env** (map[string]string) - Additional environment variables ``` -------------------------------- ### Get System Proxy Setting Source: https://github.com/gui-for-cores/gui.for.singbox/blob/main/_autodocs/api-reference/app.md Retrieves the current system proxy setting. Behavior varies by operating system: Windows reads from the registry, macOS queries System Preferences, and Linux checks environment variables and network manager settings. ```go result := app.GetSystemProxy() if result.Flag { println("Current proxy:", result.Data) } ``` -------------------------------- ### ShowMainWindow Source: https://github.com/gui-for-cores/gui.for.singbox/blob/main/_autodocs/api-reference/app.md Makes the application window visible. Shows the main window if it was hidden. Platform-specific behavior via Wails runtime. ```APIDOC ## ShowMainWindow() ### Description Makes the application window visible. Shows the main window if it was hidden. Platform-specific behavior via Wails runtime. ### Signature ```go func (a *App) ShowMainWindow() ``` ### Example ```go app.ShowMainWindow() ``` ``` -------------------------------- ### IsStartup() Source: https://github.com/gui-for-cores/gui.for.singbox/blob/main/_autodocs/api-reference/app.md Detects if the application is running for the first time in a session. This is useful for triggering one-time initialization logic. ```APIDOC ## IsStartup() ### Description Detects whether this is the application's first startup. ### Signature ```go func (a *App) IsStartup() bool ``` ### Returns - `bool`: `true` on first startup, `false` on subsequent calls. ### Example ```go if app.IsStartup() { // Initialize app data, settings, etc. } ``` ``` -------------------------------- ### Global App Configuration Source: https://github.com/gui-for-cores/gui.for.singbox/blob/main/_autodocs/api-reference/app.md The global configuration object loaded from data/user.yaml at startup. It controls various application settings like window state, GPU policy, and window dimensions. ```go var Config = &AppConfig{} ``` -------------------------------- ### ShowMainWindow() Source: https://github.com/gui-for-cores/gui.for.singbox/blob/main/_autodocs/api-reference/frontend.md Shows the main application window if it is currently hidden. ```APIDOC ## ShowMainWindow() ### Description Shows the main window if hidden. ### Method `async` ### Endpoint `bridge/app.ts` ### Parameters None ### Response #### Success Response `Promise` ``` -------------------------------- ### Default Configuration Values Source: https://github.com/gui-for-cores/gui.for.singbox/blob/main/_autodocs/configuration.md These are the default settings applied if the configuration file is missing or incomplete. They cover minimum window size, initial window state, and cache strategy. ```yaml # Minimum window size (if missing) width: 800 height: 540 # Window state (overridden if launched from task scheduler) windowStartState: 0 # Cache strategy rollingRelease: true ``` -------------------------------- ### ServerOptions Type Definition Source: https://github.com/gui-for-cores/gui.for.singbox/blob/main/_autodocs/api-reference/server.md Defines the configuration options for creating an HTTP server, including settings for static file serving, uploads, and TLS. ```go type ServerOptions struct { Cert string Key string StaticPath string StaticRoute string StaticHeaders map[string]string UploadPath string UploadRoute string UploadHeaders map[string]string MaxUploadSize int64 } ``` -------------------------------- ### Resolve Relative Path from Executable Directory Source: https://github.com/gui-for-cores/gui.for.singbox/blob/main/_autodocs/README.md Demonstrates how relative paths are resolved from the application's base directory. Use this for accessing files relative to the executable's location. ```go app.ReadFile("data/config.json", ...) // → {executable_directory}/data/config.json ``` -------------------------------- ### List Running Server IDs Source: https://github.com/gui-for-cores/gui.for.singbox/blob/main/_autodocs/api-reference/server.md Lists all currently running server IDs. The IDs are returned as a pipe-delimited string. This is useful for monitoring and managing active servers. ```Go func (a *App) ListServer() FlagResult result := app.ListServer() if result.Flag { servers := strings.Split(result.Data, "|") for _, id := range servers { println("Running:", id) } } ``` -------------------------------- ### Exported Constructor Functions Source: https://github.com/gui-for-cores/gui.for.singbox/blob/main/_autodocs/exported-symbols.md Functions for creating instances of the App and related components. ```APIDOC ## Exported Constructor Functions ### Description Functions for creating instances of the App and related components. ### Functions - `NewApp() *App`: Creates a new instance of the App. - `CreateApp(fs embed.FS) *App`: Creates a new instance of the App using embedded file system. - `CreateTray(a *App, icon []byte) (trayStart, trayEnd func())`: Creates the system tray and returns functions to start and end it. ``` -------------------------------- ### GetSystemProxy() Source: https://github.com/gui-for-cores/gui.for.singbox/blob/main/_autodocs/api-reference/frontend.md Retrieves the current system-wide proxy URL. Throws an error if the proxy information cannot be retrieved. ```APIDOC ## GetSystemProxy() ### Description Gets current system proxy URL. ### Method `async` ### Endpoint `bridge/app.ts` ### Parameters None ### Response #### Success Response `Promise` - The current system proxy URL (e.g., "http://proxy.example.com:8080"). ### Throws Error message string if unable to retrieve system proxy settings. ``` -------------------------------- ### WindowShow Source: https://github.com/gui-for-cores/gui.for.singbox/blob/main/_autodocs/exported-symbols.md Makes the application window visible. This is typically used after the window has been hidden. ```APIDOC ## WindowShow ### Description Makes the application window visible. This is typically used after the window has been hidden. ### Method `WindowShow(): void` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (void) None #### Response Example None ``` -------------------------------- ### Read File with IOOptions Source: https://github.com/gui-for-cores/gui.for.singbox/blob/main/_autodocs/api-reference/io.md Reads file contents. Use 'Text' mode for strings and 'Binary' mode for base64 encoded data. Specify 'Range' for partial reads. ```go result := app.ReadFile("config.json", IOOptions{Mode: "Text"}) if result.Flag { config := result.Data // JSON string } ``` ```go result := app.ReadFile("data.bin", IOOptions{ Mode: "Binary", Range: "0-1023", }) data, _ := base64.StdEncoding.DecodeString(result.Data) ``` -------------------------------- ### Open Directory in File Explorer Source: https://github.com/gui-for-cores/gui.for.singbox/blob/main/_autodocs/api-reference/io.md Opens a specified directory in the system's default file explorer. Works across Windows, macOS, and Linux. ```go app.OpenDir("data/logs") ``` -------------------------------- ### CopyFile: Copy File with Parent Directory Creation Source: https://github.com/gui-for-cores/gui.for.singbox/blob/main/_autodocs/api-reference/io.md Copies a file from source to destination. Creates parent directories of dst if missing. Copies file content byte-for-byte. ```go func (a *App) CopyFile(src string, dst string) FlagResult ``` ```go app.CopyFile("config.json", "config.json.backup") ``` -------------------------------- ### RestartApp() Source: https://github.com/gui-for-cores/gui.for.singbox/blob/main/_autodocs/api-reference/app.md Restarts the application by launching a new instance and closing the current one. This is useful for applying updates or recovering from certain states. ```APIDOC ## RestartApp() ### Description Restarts the application by spawning a new process and exiting the current one. ### Signature ```go func (a *App) RestartApp() FlagResult ``` ### Returns - `FlagResult`: An object containing a success flag and a status message. - `Flag` (`bool`): `true` on success, `false` on failure. - `Data` (`string`): Status message, especially on failure. ### Throws/Errors - `FlagResult.Flag=false`: If the executable is not found or the spawn process fails. ### Example ```go result := app.RestartApp() if !result.Flag { println("Restart failed:", result.Data) } ``` ``` -------------------------------- ### SetSystemProxy() Source: https://github.com/gui-for-cores/gui.for.singbox/blob/main/_autodocs/api-reference/frontend.md Configures system-wide proxy settings, allowing enabling/disabling, specifying the server address, proxy type, bypass list, and network services. ```APIDOC ## SetSystemProxy(enable: boolean, server: string, proxyType?: 'mixed' | 'http' | 'socks', bypass?: string, services?: string[]) ### Description Sets system-wide proxy settings. ### Method `async` ### Endpoint `bridge/app.ts` ### Parameters #### Path Parameters - **enable** (boolean) - Required - Enable/disable proxy - **server** (string) - Required - Proxy address (e.g., "127.0.0.1:8080") - **proxyType** (string) - Optional - Default: "mixed" - Proxy type: "mixed", "http", "socks" - **bypass** (string) - Optional - Default: "" - Comma-separated bypass list - **services** (string[]) - Optional - Default: `[]` - macOS-specific network services ### Response #### Success Response `Promise` ### Throws Error message string if setting system proxy fails. ### Example ```typescript await SetSystemProxy(true, '127.0.0.1:8080', 'http', 'localhost,127.0.0.1') ``` ``` -------------------------------- ### Tray Methods Source: https://github.com/gui-for-cores/gui.for.singbox/blob/main/_autodocs/exported-symbols.md Methods for updating the application's system tray icon and menus. ```APIDOC ## Tray Methods ### Description Methods for updating the application's system tray icon and menus. ### Methods - `UpdateTray(tray TrayContent)`: Updates the system tray icon. - `UpdateTrayMenus(menus []MenuItem)`: Updates the system tray menus. - `UpdateTrayAndMenus(tray TrayContent, menus []MenuItem)`: Updates both the system tray icon and menus. ``` -------------------------------- ### Execute Command Synchronously Source: https://github.com/gui-for-cores/gui.for.singbox/blob/main/_autodocs/api-reference/frontend.md Use Exec to run a command and wait for its output. It accepts the command path, arguments, and optional execution options like working directory or environment variables. The 'Convert' option can be used to decode GB18030 output. ```typescript export const Exec: ( path: string, args?: string[], options?: ExecOptions, ) => Promise ``` ```typescript const output = await Exec('ls', ['-la', '/tmp']) console.log(output) ``` -------------------------------- ### Check File Existence Source: https://github.com/gui-for-cores/gui.for.singbox/blob/main/_autodocs/api-reference/io.md Verifies if a file or directory exists at the given path. Returns a FlagResult indicating existence. ```go func (a *App) FileExists(path string) FlagResult ``` ```go result := app.FileExists("config.json") if result.Flag && result.Data == "true" { println("File exists") } ``` -------------------------------- ### handleFileDownload Source: https://github.com/gui-for-cores/gui.for.singbox/blob/main/_autodocs/api-reference/server.md Serves static files with custom headers, applying specified headers to the response and delegating the actual file serving to `http.FileServer`. ```APIDOC ## handleFileDownload(w http.ResponseWriter, r *http.Request, fs http.Handler, headers map[string]string) ### Description Serves static files with custom headers, applying specified headers to the response and delegating the actual file serving to `http.FileServer`. Responds to OPTIONS requests with 204 No Content. ### Method (Not specified, likely an internal handler function) ### Endpoint (Not specified) ### Parameters (Not applicable, uses http.ResponseWriter, http.Request, http.Handler, and map) ### Request Example (Not specified) ### Response (Not specified, serves files) ### Behavior: - Applies StaticHeaders to response. - Responds to OPTIONS with 204 No Content. - Delegates file serving to http.FileServer. ``` -------------------------------- ### ExecBackground() Source: https://github.com/gui-for-cores/gui.for.singbox/blob/main/_autodocs/api-reference/frontend.md Executes a command asynchronously with output streaming. ```APIDOC ## ExecBackground() ### Description Executes command asynchronously with output streaming. ### Method Signature ```typescript ExecBackground(path: string, args?: string[], onOut?: (out: string) => void, onEnd?: (out: string) => void, options?: ExecOptions): Promise ``` ### Parameters #### Path Parameters - **path** (string) - Executable path #### Arguments - **args** (string[]) - Arguments #### Callbacks - **onOut** (function) - Called for each output line - **onEnd** (function) - Called when process ends #### Options - **options** (object) - Execution options - **WorkingDirectory** (string) - Working directory ### Returns Process ID ### Example ```typescript const pid = await ExecBackground( 'python3', ['script.py'], (line) => console.log('Output:', line), (endData) => console.log('Done:', endData), { WorkingDirectory: '/home/user' } ) ``` ``` -------------------------------- ### Perform HTTP Request Source: https://github.com/gui-for-cores/gui.for.singbox/blob/main/_autodocs/api-reference/network.md Performs an HTTP request with specified method, URL, headers, body, and optional configuration. Handles basic requests, POST with headers, and Server-Sent Events streaming. ```go // Basic request result := app.Requests("GET", "https://api.example.com/data", nil, "", RequestOptions{}) // POST with headers result := app.Requests( "POST", "https://api.example.com/upload", map[string]string{ "Content-Type": "application/json", "Authorization": "Bearer token123", }, `{"name":"value"}`, RequestOptions{Timeout: 30}, ) // Server-Sent Events streaming result := app.Requests( "GET", "https://api.example.com/events", nil, "", RequestOptions{Stream: "onStreamEvent"}, ) // Frontend: runtime.EventsOn("onStreamEvent", (event) => { ... }) ``` -------------------------------- ### WriteFile Function Source: https://github.com/gui-for-cores/gui.for.singbox/blob/main/_autodocs/api-reference/io.md Writes data to a file. Supports text and binary modes, and allows for range-based updates. Parent directories are created automatically. Binary mode requires base64 encoded content. ```go func (a *App) WriteFile(path string, content string, options IOOptions) FlagResult ``` ```go // Write full file result := app.WriteFile("config.json", `{"key": "value"}`, IOOptions{Mode: "Text"}) ``` ```go // Update bytes 100-199 data := []byte("x") * 100 encoded := base64.StdEncoding.EncodeToString(data) app.WriteFile("data.bin", encoded, IOOptions{Mode: "Binary", Range: "100-199"}) ``` -------------------------------- ### Open Directory Source: https://github.com/gui-for-cores/gui.for.singbox/blob/main/_autodocs/api-reference/frontend.md Opens a specified directory in the system's default file manager. ```typescript export const OpenDir: (path: string) => Promise ``` -------------------------------- ### ListServer() Source: https://github.com/gui-for-cores/gui.for.singbox/blob/main/_autodocs/api-reference/frontend.md Lists the IDs of all currently running HTTP servers. ```APIDOC ## ListServer() ### Description Lists the IDs of all currently running HTTP servers. ### Method Signature ```typescript export const ListServer: () => Promise ``` ``` -------------------------------- ### ListServer Source: https://github.com/gui-for-cores/gui.for.singbox/blob/main/_autodocs/api-reference/server.md Lists all currently running server IDs. The IDs are returned as a pipe-delimited string. ```APIDOC ## ListServer() ### Description Lists all currently running server IDs. The IDs are returned as a pipe-delimited string. ### Method (Not specified, likely a method call on an App object) ### Parameters (Not applicable) ### Request Example ```go result := app.ListServer() if result.Flag { servers := strings.Split(result.Data, "|") for _, id := range servers { println("Running:", id) } } ``` ### Response #### Success Response Returns a `FlagResult` where `Data` contains a pipe-delimited string of server IDs. #### Response Example (Not specified) ``` -------------------------------- ### Download() Source: https://github.com/gui-for-cores/gui.for.singbox/blob/main/_autodocs/api-reference/frontend.md Downloads a file from a given URL to a specified path, with optional progress reporting. ```APIDOC ## Download() ### Description Downloads a file from a given URL to a specified path, with optional progress reporting. ### Method Signature ```typescript export const Download: (url: string, path: string, headers?: Request['headers'], progress?: (loaded: number, total: number) => void, options?: Request['options']) => Promise ``` ### Example ```typescript await Download( 'https://example.com/file.zip', 'downloads/file.zip', {}, (loaded, total) => console.log(`${loaded}/${total}`), { Sha256: 'abc123...' } ) ``` ```