### Start Xray from Inline JSON Configuration Source: https://context7.com/xtls/libxray/llms.txt Starts an Xray instance with an in-memory JSON configuration. This is useful when the configuration is constructed dynamically. The `datDir` must be provided. ```go configJSON := `{ "inbounds": [{"port": 1080, "protocol": "socks", "tag": "socks-in"}], "outbounds": [{"protocol": "freedom", "tag": "direct"}] }` type RunXrayFromJSONRequest struct { DatDir string `json:"datDir"` ConfigJSON string `json:"configJSON"` } req := RunXrayFromJSONRequest{ DatDir: "/data/app/geo", ConfigJSON: configJSON, } reqBytes, _ := json.Marshal(req) b64 := base64.StdEncoding.EncodeToString(reqBytes) result := libXray.RunXrayFromJSON(b64) // {"success":true} ``` -------------------------------- ### Start Xray from Config File Path Source: https://context7.com/xtls/libxray/llms.txt Starts an Xray instance using a configuration file. Ensure geo-data directories and config file exist. The function returns a Base64 encoded JSON string indicating success or failure. ```go package main import ( "encoding/base64" "encoding/json" "fmt" libXray "github.com/xtls/libxray" ) func main() { type RunXrayRequest struct { DatDir string `json:"datDir"` MphCachePath string `json:"mphCachePath,omitempty"` ConfigPath string `json:"configPath"` } req := RunXrayRequest{ DatDir: "/data/app/geo", // directory containing geosite.dat and geoip.dat ConfigPath: "/data/app/config.json", } reqBytes, _ := json.Marshal(req) b64 := base64.StdEncoding.EncodeToString(reqBytes) result := libXray.RunXray(b64) // result is a Base64 JSON: {"success":true} or {"success":false,"error":"..."} fmt.Println(result) // Check state running := libXray.GetXrayState() // true if the instance is running fmt.Println("running:", running) // Stop stopResult := libXray.StopXray() fmt.Println(stopResult) } ``` -------------------------------- ### Build libXray for Windows Source: https://github.com/xtls/libxray/blob/main/README.md Compile libXray for Windows. Requires git, go, and MinGW. LLVM MinGW or WinLibs can be installed via winget. ```shell python3 build/main.py windows ``` -------------------------------- ### RunXray Source: https://context7.com/xtls/libxray/llms.txt Starts an Xray instance using a configuration file path. It initializes the geo-data environment and forces a GC sweep before starting the core engine. The function accepts a Base64-encoded JSON request and returns a Base64-encoded CallResponse. ```APIDOC ## RunXray ### Description Starts an Xray instance using a configuration file path. It initializes the geo-data environment and forces a GC sweep before starting the core engine. The function accepts a Base64-encoded JSON request and returns a Base64-encoded CallResponse. ### Method libXray.RunXray ### Parameters #### Request Body - **datDir** (string) - Required - Directory containing geosite.dat and geoip.dat. - **mphCachePath** (string) - Optional - Path to the MPH cache file. - **configPath** (string) - Required - Path to the Xray configuration JSON file. ### Request Example ```go package main import ( "encoding/base64" "encoding/json" "fmt" libXray "github.com/xtls/libxray" ) func main() { type RunXrayRequest struct { DatDir string `json:"datDir"` MphCachePath string `json:"mphCachePath,omitempty"` ConfigPath string `json:"configPath"` } req := RunXrayRequest{ DatDir: "/data/app/geo", // directory containing geosite.dat and geoip.dat ConfigPath: "/data/app/config.json", } reqBytes, _ := json.Marshal(req) b64 := base64.StdEncoding.EncodeToString(reqBytes) result := libXray.RunXray(b64) // result is a Base64 JSON: {"success":true} or {"success":false,"error":"..."} fmt.Println(result) // Check state running := libXray.GetXrayState() // true if the instance is running fmt.Println("running:", running) // Stop stopResult := libXray.StopXray() fmt.Println(stopResult) } ``` ### Response #### Success Response (200) - **success** (bool) - Indicates if the operation was successful. - **data** (any) - The data returned by the operation (if successful). #### Error Response - **success** (bool) - Always false. - **error** (string) - Description of the error. ### Response Example ```json { "success": true } ``` ```json { "success": false, "error": "Error message details" } ``` ``` -------------------------------- ### Install WinLibs MinGW via winget Source: https://github.com/xtls/libxray/blob/main/README.md Installs WinLibs MinGW using the Windows Package Manager. ```shell winget install BrechtSanders.WinLibs.POSIX.UCRT ``` -------------------------------- ### Install LLVM MinGW via winget Source: https://github.com/xtls/libxray/blob/main/README.md Installs LLVM MinGW using the Windows Package Manager. ```shell winget install MartinStorsjo.LLVM-MinGW.UCRT ``` -------------------------------- ### Standalone Xray runner for Linux/Windows Source: https://context7.com/xtls/libxray/llms.txt The `desktop_bin` provides a standalone Xray runner for Linux and Windows. It initializes IP routing, overrides DNS, starts Xray, and runs until terminated. It uses a JSON launcher config to set up the environment. ```APIDOC ## `desktop_bin` — Standalone Xray runner for Linux/Windows A minimal `main` package that reads a JSON launcher config, initialises IP routing (Linux), overrides the DNS resolver, starts Xray, and blocks until SIGTERM/SIGINT. ### Configuration Example (`launcher-config.json`) ```json { "tunName": "tun0", "tunPriority": 100, "dns": "8.8.8.8:53", "bindInterface": "eth0", "datDir": "/usr/local/share/xray", "mphCachePath": "/var/cache/xray/mph.cache", "configPath": "/etc/xray/config.json" } ``` ### Build and Run **Build:** ```bash go build -o xray-desktop ./desktop_bin ``` **Run:** (blocks until Ctrl-C or SIGTERM) ```bash ./xray-desktop -configPath launcher-config.json ``` ``` -------------------------------- ### Build Xray Run Requests Source: https://context7.com/xtls/libxray/llms.txt Helper functions to simplify the creation of Base64-encoded JSON requests for starting Xray instances, either from a config file or inline JSON. Handles JSON marshalling and encoding. ```go // Build request for file-based start b64, err := libXray.NewXrayRunRequest( "/data/app/geo", // datDir "/data/app/mph.cache", // mphCachePath (empty string to skip) "/data/app/config.json", // configPath ) if err != nil { panic(err) } result := libXray.RunXray(b64) // Build request for inline-JSON start b64json, err := libXray.NewXrayRunFromJSONRequest( "/data/app/geo", "", `{"inbounds":[...],"outbounds":[...]}`, ) result2 := libXray.RunXrayFromJSON(b64json) ``` -------------------------------- ### Inject TUN file descriptor before starting Xray Source: https://context7.com/xtls/libxray/llms.txt On platforms where the TUN device is opened by the host application (e.g., Android VpnService), pass the file descriptor to Xray before calling `RunXray` or `RunXrayFromJSON`. ```go // Must be called BEFORE RunXray / RunXrayFromJSON libXray.SetTunFd(int32(tunFd)) b64, _ := libXray.NewXrayRunRequest("/data/app/geo", "", "/data/app/config.json") libXray.RunXray(b64) ``` -------------------------------- ### RunXrayFromJSON Source: https://context7.com/xtls/libxray/llms.txt Starts an Xray instance using an inline JSON string for the configuration. This is useful when the host application constructs the Xray configuration in memory. It accepts a Base64-encoded JSON request and returns a Base64-encoded CallResponse. ```APIDOC ## RunXrayFromJSON ### Description Starts an Xray instance using an inline JSON string for the configuration. This is useful when the host application constructs the Xray configuration in memory. It accepts a Base64-encoded JSON request and returns a Base64-encoded CallResponse. ### Method libXray.RunXrayFromJSON ### Parameters #### Request Body - **datDir** (string) - Required - Directory containing geosite.dat and geoip.dat. - **configJSON** (string) - Required - The full Xray configuration JSON string. ### Request Example ```go configJSON := `{ "inbounds": [{"port": 1080, "protocol": "socks", "tag": "socks-in"}], "outbounds": [{"protocol": "freedom", "tag": "direct"}] }` type RunXrayFromJSONRequest struct { DatDir string `json:"datDir"` ConfigJSON string `json:"configJSON"` } req := RunXrayFromJSONRequest{ DatDir: "/data/app/geo", ConfigJSON: configJSON, } reqBytes, _ := json.Marshal(req) b64 := base64.StdEncoding.EncodeToString(reqBytes) result := libXray.RunXrayFromJSON(b64) // {"success":true} ``` ### Response #### Success Response (200) - **success** (bool) - Indicates if the operation was successful. #### Error Response - **success** (bool) - Always false. - **error** (string) - Description of the error. ### Response Example ```json { "success": true } ``` ``` -------------------------------- ### Get Xray-core Version Source: https://context7.com/xtls/libxray/llms.txt Retrieves the version string of the embedded Xray-core. The result is Base64 encoded JSON containing the version information. ```go result := libXray.XrayVersion() decoded, _ := base64.StdEncoding.DecodeString(result) // {"success":true,"data":"1.260327.0"} fmt.Println(string(decoded)) ``` -------------------------------- ### NewXrayRunRequest / NewXrayRunFromJSONRequest Source: https://context7.com/xtls/libxray/llms.txt Convenience functions to build and Base64-encode the request structs for starting Xray instances, eliminating the need for manual JSON marshalling in the caller. ```APIDOC ## NewXrayRunRequest / NewXrayRunFromJSONRequest ### Description Convenience functions to build and Base64-encode the request structs for starting Xray instances, eliminating the need for manual JSON marshalling in the caller. ### Method libXray.NewXrayRunRequest(datDir, mphCachePath, configPath) libXray.NewXrayRunFromJSONRequest(datDir, configJSON) ### Parameters #### NewXrayRunRequest - **datDir** (string) - Required - Directory containing geosite.dat and geoip.dat. - **mphCachePath** (string) - Optional - Path to the MPH cache file (empty string to skip). - **configPath** (string) - Required - Path to the Xray configuration JSON file. #### NewXrayRunFromJSONRequest - **datDir** (string) - Required - Directory containing geosite.dat and geoip.dat. - **configJSON** (string) - Required - The full Xray configuration JSON string. ### Request Example ```go // Build request for file-based start b64, err := libXray.NewXrayRunRequest( "/data/app/geo", // datDir "/data/app/mph.cache", // mphCachePath (empty string to skip) "/data/app/config.json", // configPath ) if err != nil { panic(err) } result := libXray.RunXray(b64) // Build request for inline-JSON start b64json, err := libXray.NewXrayRunFromJSONRequest( "/data/app/geo", "", // mphCachePath `{"inbounds":[...],"outbounds":[...]}`, ) result2 := libXray.RunXrayFromJSON(b64json) ``` ### Response - **b64** (string) - Base64-encoded JSON request string. - **err** (error) - An error if the request could not be built. ``` -------------------------------- ### Get Xray State Source: https://context7.com/xtls/libxray/llms.txt Checks if an Xray instance is currently running. Returns a plain boolean value, not Base64 encoded. ```go if libXray.GetXrayState() { fmt.Println("Xray is active") } else { fmt.Println("Xray is stopped") } ``` -------------------------------- ### SetTunFd Source: https://context7.com/xtls/libxray/llms.txt Injects a TUN file descriptor into Xray. This is used on platforms where the TUN device is opened by the host application, such as Android's VpnService, before Xray is started. ```APIDOC ## SetTunFd ### Description Injects a TUN file descriptor before starting Xray. On platforms where the TUN device is opened by the host application (e.g., Android VpnService), pass the file descriptor to Xray before calling `RunXray`. ### Method `libXray.SetTunFd(tunFd int32)` ### Parameters * `tunFd` (int32) - The file descriptor of the TUN device. ### Usage Example ```go // Must be called BEFORE RunXray / RunXrayFromJSON libXray.SetTunFd(int32(tunFd)) b64, _ := libXray.NewXrayRunRequest("/data/app/geo", "", "/data/app/config.json") libXray.RunXray(b64) ``` ``` -------------------------------- ### Android: Register socket protection callbacks Source: https://context7.com/xtls/libxray/llms.txt On Android, sockets opened by Xray must be protected (excluded from VPN) to prevent routing loops. Implement the `DialerController` interface and pass it to these functions before starting Xray. ```kotlin // Kotlin (Android) — called via gomobile binding class MyVpnService : VpnService() { fun startProxy() { val controller = object : LibXray.DialerController { override fun protectFd(fd: Int): Boolean = protect(fd) } LibXray.registerDialerController(controller) LibXray.registerListenerController(controller) val b64 = LibXray.newXrayRunRequest("/data/data/app/geo", "", "/data/data/app/config.json") LibXray.runXray(b64) } } ``` -------------------------------- ### Validate Xray Config with TestXray Source: https://context7.com/xtls/libxray/llms.txt Use TestXray to validate a configuration file without starting an Xray instance. It returns success if the config is valid, or an error detailing the first validation failure encountered. ```go type RunXrayRequest struct { DatDir string `json:"datDir"` ConfigPath string `json:"configPath"` } req := RunXrayRequest{ DatDir: "/data/app/geo", ConfigPath: "/data/app/config.json", } reqBytes, _ := json.Marshal(req) b64 := base64.StdEncoding.EncodeToString(reqBytes) result := libXray.TestXray(b64) decoded, _ := base64.StdEncoding.DecodeString(result) // {"success":true} — config is valid // {"success":false,"error":"failed to parse config: ..."} — invalid config fmt.Println(string(decoded)) ``` -------------------------------- ### Measure Latency with Ping Source: https://context7.com/xtls/libxray/llms.txt Measure round-trip latency through an Xray outbound by starting a temporary instance, performing a HEAD request, and then tearing it down. Returns latency in milliseconds, or sentinel values for errors and timeouts. ```go type pingRequest struct { DatDir string `json:"datDir"` ConfigPath string `json:"configPath"` Timeout int `json:"timeout"` // seconds Url string `json:"url"` Proxy string `json:"proxy"` // e.g. "socks5://[::1]:1080" } pingReq := pingRequest{ DatDir: "/data/app/geo", ConfigPath: "/data/app/config.json", Timeout: 10, Url: "https://www.google.com", Proxy: "socks5://[::1]:1080", } reqBytes, _ := json.Marshal(pingReq) b64 := base64.StdEncoding.EncodeToString(reqBytes) result := libXray.Ping(b64) decoded, _ := base64.StdEncoding.DecodeString(result) // {"success":true,"data":342} — 342 ms latency // {"success":false,"data":11000,...} — timed out // {"success":false,"data":10000,...} — connection error fmt.Println(string(decoded)) ``` -------------------------------- ### Ping Source: https://context7.com/xtls/libxray/llms.txt Measures the round-trip latency through a specified Xray outbound proxy. It starts a temporary Xray instance, performs a HEAD request, and then tears down the instance. Returns latency in milliseconds on success, or specific sentinel values for errors and timeouts. ```APIDOC ## Ping ### Description Measures round-trip latency through an Xray outbound. Starts a temporary Xray instance from the given config, performs a HEAD request through the configured outbound proxy, then tears the instance down. Returns milliseconds on success, or sentinel values `10000` (error) / `11000` (timeout). ### Method libXray.Ping ### Parameters #### Request Body (Base64 encoded JSON string) - **datDir** (string) - Required - The directory containing Xray data files. - **configPath** (string) - Required - The path to the Xray configuration file. - **timeout** (int) - Optional - The timeout in seconds for the latency test. - **url** (string) - Required - The URL to perform the HEAD request against. - **proxy** (string) - Required - The proxy address to use (e.g., "socks5://[::1]:1080"). ### Request Example ```go type pingRequest struct { DatDir string `json:"datDir"` ConfigPath string `json:"configPath"` Timeout int `json:"timeout"` // seconds Url string `json:"url"` Proxy string `json:"proxy"` // e.g. "socks5://[::1]:1080" } req := pingRequest{ DatDir: "/data/app/geo", ConfigPath: "/data/app/config.json", Timeout: 10, Url: "https://www.google.com", Proxy: "socks5://[::1]:1080", } reqBytes, _ := json.Marshal(req) b64 := base64.StdEncoding.EncodeToString(reqBytes) result := libXray.Ping(b64) ``` ### Response #### Success Response - **success** (bool) - Indicates if the latency test was successful. - **data** (int) - The measured latency in milliseconds. #### Response Example ```json {"success":true,"data":342} // 342 ms latency ``` #### Error Handling - **success** (bool) - Indicates failure. - **data** (int) - Sentinel value `10000` for connection error or `11000` for timeout. #### Response Example ```json {"success":false,"data":11000,...} // timed out ``` ```json {"success":false,"data":10000,...} // connection error ``` ``` -------------------------------- ### Build and Run Xray Desktop Runner Source: https://context7.com/xtls/libxray/llms.txt Build the standalone Xray runner for Linux/Windows and run it with a launcher configuration file. The runner blocks until interrupted. ```json // launcher-config.json { "tunName": "tun0", "tunPriority": 100, "dns": "8.8.8.8:53", "bindInterface": "eth0", "datDir": "/usr/local/share/xray", "mphCachePath": "/var/cache/xray/mph.cache", "configPath": "/etc/xray/config.json" } ``` ```bash # Build go build -o xray-desktop ./desktop_bin # Run (blocks until Ctrl-C or SIGTERM) ./xray-desktop -configPath launcher-config.json ``` -------------------------------- ### Build libXray for Linux Source: https://github.com/xtls/libxray/blob/main/README.md Compile libXray for Linux. Requires git, go, gcc, and g++. ```shell python3 build/main.py linux ``` -------------------------------- ### Build libXray for Apple (gomobile) Source: https://github.com/xtls/libxray/blob/main/README.md Compile libXray for Apple platforms using gomobile. Supports iOS, iOSSimulator, macOS, and macCatalyst. Does not support tvOS and may cause warnings for minimum macOS version. ```shell python3 build/main.py apple gomobile ``` -------------------------------- ### Build libXray for Apple (go) Source: https://github.com/xtls/libxray/blob/main/README.md Compile libXray for Apple platforms using the go toolchain. Supports iOS, iOSSimulator, macOS, and macCatalyst. ```shell python3 build/main.py apple go ``` -------------------------------- ### Build MPH Cache with BuildMphCache Source: https://context7.com/xtls/libxray/llms.txt Pre-build a Minimal Perfect Hash cache for faster domain routing lookups. Pass the resulting cache path to RunXray or RunXrayFromJSON using the mphCachePath parameter. ```go type RunXrayRequest struct { DatDir string `json:"datDir"` MphCachePath string `json:"mphCachePath"` ConfigPath string `json:"configPath"` } req := RunXrayRequest{ DatDir: "/data/app/geo", MphCachePath: "/data/app/mph.cache", ConfigPath: "/data/app/config.json", } reqBytes, _ := json.Marshal(req) b64 := base64.StdEncoding.EncodeToString(reqBytes) result := libXray.BuildMphCache(b64) decoded, _ := base64.StdEncoding.DecodeString(result) // {"success":true} fmt.Println(string(decoded)) ``` -------------------------------- ### Build libXray for Android Source: https://github.com/xtls/libxray/blob/main/README.md Compile libXray for Android. Requires git and go. Minimum Android API level is 21. ```shell python3 build/main.py android ``` -------------------------------- ### BuildMphCache Source: https://context7.com/xtls/libxray/llms.txt Pre-builds a Minimal Perfect Hash (MPH) cache for routing rules. This significantly speeds up domain routing lookups. The resulting cache path can be passed to `RunXray` or `RunXrayFromJSON` via the `mphCachePath` parameter. ```APIDOC ## BuildMphCache ### Description Pre-builds a Minimal Perfect Hash cache for routing rules. Building an MPH cache significantly speeds up domain routing lookups. Pass the resulting cache path to `RunXray` / `RunXrayFromJSON` via `mphCachePath`. ### Method libXray.BuildMphCache ### Parameters #### Request Body (Base64 encoded JSON string) - **datDir** (string) - Required - The directory containing Xray data files. - **mphCachePath** (string) - Required - The path where the MPH cache will be saved. - **configPath** (string) - Required - The path to the Xray configuration file. ### Request Example ```go type RunXrayRequest struct { DatDir string `json:"datDir"` MphCachePath string `json:"mphCachePath"` ConfigPath string `json:"configPath"` } req := RunXrayRequest{ DatDir: "/data/app/geo", MphCachePath: "/data/app/mph.cache", ConfigPath: "/data/app/config.json", } reqBytes, _ := json.Marshal(req) b64 := base64.StdEncoding.EncodeToString(reqBytes) result := libXray.BuildMphCache(b64) ``` ### Response #### Success Response - **success** (bool) - Indicates if the MPH cache was built successfully. #### Response Example ```json {"success":true} ``` ``` -------------------------------- ### TestXray Source: https://context7.com/xtls/libxray/llms.txt Validates a configuration file by loading and immediately closing an Xray instance. It returns success if the configuration is valid, or an error detailing the first validation failure encountered. ```APIDOC ## TestXray ### Description Validates a config file without running Xray. Loads and immediately closes the Xray instance. Returns success if the config is valid, or an error describing the first validation failure. ### Method libXray.TestXray ### Parameters #### Request Body (Base64 encoded JSON string) - **datDir** (string) - Required - The directory containing Xray data files. - **configPath** (string) - Required - The path to the Xray configuration file. ### Request Example ```go type RunXrayRequest struct { DatDir string `json:"datDir"` ConfigPath string `json:"configPath"` } req := RunXrayRequest{ DatDir: "/data/app/geo", ConfigPath: "/data/app/config.json", } reqBytes, _ := json.Marshal(req) b64 := base64.StdEncoding.EncodeToString(reqBytes) result := libXray.TestXray(b64) ``` ### Response #### Success Response - **success** (bool) - Indicates if the configuration is valid. - **error** (string) - Description of the validation error if `success` is false. #### Response Example ```json {"success":true} ``` ```json {"success":false,"error":"failed to parse config: ..."} ``` ``` -------------------------------- ### Fetch Traffic Stats with QueryStats Source: https://context7.com/xtls/libxray/llms.txt Fetch inbound/outbound traffic counters via the metrics endpoint. Requires the Xray instance to be running as a child process with a 'metrics' block configured. Returns the raw JSON body from the /debug/vars endpoint. ```json { "metrics": { "tag": "metrics", "listen": "[::1]:49227" }, "policy": { "system": { "statsInboundDownlink": true, "statsInboundUplink": true, "statsOutboundDownlink": true, "statsOutboundUplink": true } }, "stats": {} } ``` ```go serverAddr := "http://[::1]:49227/debug/vars" b64 := base64.StdEncoding.EncodeToString([]byte(serverAddr)) result := libXray.QueryStats(b64) decoded, _ := base64.StdEncoding.DecodeString(result) // {"success":true,"data":"{\"cmdline\":[...],\"stats\":{...}}"} fmt.Println(string(decoded)) ``` -------------------------------- ### Discover available TCP ports Source: https://context7.com/xtls/libxray/llms.txt Asks the kernel for a specified number of available TCP ports. Useful for dynamically assigning ports to Xray listeners before writing the configuration. ```go result := libXray.GetFreePorts(3) decoded, _ := base64.StdEncoding.DecodeString(result) // {"success":true,"data":{"ports":[51234,51235,51236]}} fmt.Println(string(decoded)) ``` -------------------------------- ### Convert Xray JSON config to share links Source: https://context7.com/xtls/libxray/llms.txt Serializes an Xray JSON configuration into shareable URI links. The `sendThrough` field of each outbound is used as the link name/fragment. VMess outbounds produce VMessAEAD links. ```go xrayJSON := `{ "outbounds": [ { "protocol": "vless", "sendThrough": "MyServer", "settings": { "address": "example.com", "port": 443, "id": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", "encryption": "none", "flow": "xtls-rprx-vision" }, "streamSettings": { "network": "raw", "security": "reality", "realitySettings": { "fingerprint": "chrome", "serverName": "example.com", "publicKey": "...", "shortId": "abcdef12" } } } ] }` b64 := base64.StdEncoding.EncodeToString([]byte(xrayJSON)) result := libXray.ConvertXrayJsonToShareLinks(b64) decoded, _ := base64.StdEncoding.DecodeString(result) // {"success":true,"data":"vless://xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx@example.com:443?flow=xtls-rprx-vision&...#MyServer"} fmt.Println(string(decoded)) ``` -------------------------------- ### Convert Share Links with ConvertShareLinksToXrayJson Source: https://context7.com/xtls/libxray/llms.txt Parse various proxy share links (vless, vmess, ss, socks, trojan, hysteria2) and Clash.Meta YAML documents into an Xray JSON config. Accepts a Base64-encoded string containing the input. ```go // Example: two share links (VLESS + Shadowsocks) links := `vless://uuid@example.com:443?encryption=none&security=tls&type=ws&path=%2Fws#MyVless ss://base64encoded@example.com:8388#MySS` b64 := base64.StdEncoding.EncodeToString([]byte(links)) result := libXray.ConvertShareLinksToXrayJson(b64) decoded, _ := base64.StdEncoding.DecodeString(result) // {"success":true,"data":{"outbounds":[{"protocol":"vless",...},{"protocol":"shadowsocks",...}]}} fmt.Println(string(decoded)) ``` ```go // Example: Clash.Meta YAML clashYaml := `proxies: - name: MyProxy type: vmess server: example.com port: 443 uuid: "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" cipher: auto tls: true` b64Clash := base64.StdEncoding.EncodeToString([]byte(clashYaml)) result2 := libXray.ConvertShareLinksToXrayJson(b64Clash) ``` -------------------------------- ### Xray Stats Configuration Source: https://github.com/xtls/libxray/blob/main/README.md Configuration for enabling Xray-core stats collection. Requires Xray-core to be run in a child process when metrics are enabled. Ensure 'metrics' is null when testing latency or validating configuration. ```json { "metrics" : { "tag" : "metrics", "listen": "[::1]:49227", }, "policy" : { "system" : { "statsInboundDownlink" : true, "statsInboundUplink" : true, "statsOutboundDownlink" : true, "statsOutboundUplink" : true } }, "stats" : {} } ``` -------------------------------- ### Count GeoData summary Source: https://context7.com/xtls/libxray/llms.txt Parses a `.dat` geo file (geosite.dat or geoip.dat), counts categories and rules, and writes a summary JSON file. `geoType` must be either `"domain"` or `"ip"`. ```go type CountGeoDataRequest struct { DatDir string `json:"datDir"` Name string `json:"name"` // e.g. "geosite" or "geoip" GeoType string `json:"geoType"` // "domain" or "ip" } req := CountGeoDataRequest{ DatDir: "/data/app/geo", Name: "geosite", GeoType: "domain", } reqBytes, _ := json.Marshal(req) b64 := base64.StdEncoding.EncodeToString(reqBytes) result := libXray.CountGeoData(b64) decoded, _ := base64.StdEncoding.DecodeString(result) // {"success":true} // Writes /data/app/geo/geosite.json: // {"codes":[{"code":"CATEGORY-ADS","ruleCount":1234},...], "categoryCount":200, "ruleCount":500000} fmt.Println(string(decoded)) ``` -------------------------------- ### GetXrayState Source: https://context7.com/xtls/libxray/llms.txt Queries the current state of the Xray instance. Returns a plain boolean value indicating whether the core instance is running. ```APIDOC ## GetXrayState ### Description Queries the current state of the Xray instance. Returns a plain boolean value indicating whether the core instance is running. ### Method libXray.GetXrayState ### Request Example ```go if libXray.GetXrayState() { fmt.Println("Xray is active") } else { fmt.Println("Xray is stopped") } ``` ### Response - **running** (bool) - `true` if the Xray instance is running, `false` otherwise. ``` -------------------------------- ### Extract geo file names from Xray config Source: https://context7.com/xtls/libxray/llms.txt Scans routing rules and DNS entries in an Xray config for `geosite:` and `geoip:` references to return a list of used `.dat` filenames. Handles custom `ext:` references as well. ```go xrayConfigBytes, _ := os.ReadFile("/data/app/config.json") b64 := base64.StdEncoding.EncodeToString(xrayConfigBytes) result := libXray.ReadGeoFiles(b64) decoded, _ := base64.StdEncoding.DecodeString(result) // {"success":true,"data":{"domain":["geosite.dat"],"ip":["geoip.dat","custom.dat"]}} fmt.Println(string(decoded)) ``` -------------------------------- ### ConvertShareLinksToXrayJson Source: https://context7.com/xtls/libxray/llms.txt Parses various proxy share link formats into an Xray JSON configuration. It accepts Base64-encoded strings containing raw Xray JSON, plain share-link lines, a block of Base64-encoded share-link lines, or a Clash.Meta YAML document. Supported schemes include `vless://`, `vmess://`, `ss://`, `socks://`, `trojan://`, and `hysteria2://` / `hy2://`. ```APIDOC ## ConvertShareLinksToXrayJson ### Description Parse proxy share links into an Xray JSON config. Accepts a Base64-encoded string that contains one of: a raw Xray JSON object, plain share-link lines (one per line), a Base64-encoded block of share-link lines, or a Clash.Meta YAML document. Supported schemes: `vless://`, `vmess://`, `ss://`, `socks://`, `trojan://`, `hysteria2://` / `hy2://`. ### Method libXray.ConvertShareLinksToXrayJson ### Parameters #### Request Body (Base64 encoded string) - **input** (string) - Required - A Base64 encoded string containing one of the supported input formats (Xray JSON, share links, or Clash.Meta YAML). ### Request Example (Multiple Share Links) ```go // Example: two share links (VLESS + Shadowsocks) links := `vless://uuid@example.com:443?encryption=none&security=tls&type=ws&path=%2Fws#MyVless ss://base64encoded@example.com:8388#MySS` b64 := base64.StdEncoding.EncodeToString([]byte(links)) result := libXray.ConvertShareLinksToXrayJson(b64) ``` ### Request Example (Clash.Meta YAML) ```go // Example: Clash.Meta YAML clashYaml := `proxies: - name: MyProxy type: vmess server: example.com port: 443 uuid: "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" cipher: auto tls: true` b64Clash := base64.StdEncoding.EncodeToString([]byte(clashYaml)) result2 := libXray.ConvertShareLinksToXrayJson(b64Clash) ``` ### Response #### Success Response - **success** (bool) - Indicates if the conversion was successful. - **data** (object) - An Xray JSON configuration object, including outbound configurations. #### Response Example ```json {"success":true,"data":{"outbounds":[{"protocol":"vless",...},{"protocol":"shadowsocks",...}]}} ``` ``` -------------------------------- ### QueryStats Source: https://context7.com/xtls/libxray/llms.txt Fetches inbound and outbound traffic counters via the metrics endpoint. This requires the Xray instance to be running as a child process with a `metrics` block configured in its configuration. Returns the raw JSON body from the `/debug/vars` endpoint. ```APIDOC ## QueryStats ### Description Fetch inbound/outbound traffic counters via the metrics endpoint. Requires the Xray instance to be running as a **child process** with a `metrics` block configured. Returns the raw JSON body from the `/debug/vars` endpoint. ### Method libXray.QueryStats ### Parameters #### Request Body (Base64 encoded string) - **serverAddr** (string) - Required - The address of the metrics endpoint (e.g., "http://[::1]:49227/debug/vars"). ### Configuration Snippet Required ```json { "metrics": { "tag": "metrics", "listen": "[::1]:49227" }, "policy": { "system": { "statsInboundDownlink": true, "statsInboundUplink": true, "statsOutboundDownlink": true, "statsOutboundUplink": true } }, "stats": {} } ``` ### Request Example ```go serverAddr := "http://[::1]:49227/debug/vars" b64 := base64.StdEncoding.EncodeToString([]byte(serverAddr)) result := libXray.QueryStats(b64) ``` ### Response #### Success Response - **success** (bool) - Indicates if the stats were fetched successfully. - **data** (string) - A JSON string containing the raw data from the metrics endpoint, including command line arguments and statistics. #### Response Example ```json {"success":true,"data":"{\"cmdline\":[...],\"stats\":{...}}"} ``` ``` -------------------------------- ### XrayVersion Source: https://context7.com/xtls/libxray/llms.txt Retrieves the version string of the embedded Xray-core. The result is Base64-encoded JSON containing the success status and the version data. ```APIDOC ## XrayVersion ### Description Retrieves the version string of the embedded Xray-core. The result is Base64-encoded JSON containing the success status and the version data. ### Method libXray.XrayVersion ### Request Example ```go result := libXray.XrayVersion() decoded, _ := base64.StdEncoding.DecodeString(result) // {"success":true,"data":"1.260327.0"} fmt.Println(string(decoded)) ``` ### Response #### Success Response (200) - **success** (bool) - Indicates if the operation was successful. - **data** (string) - The Xray-core version string. #### Error Response - **success** (bool) - Always false. - **error** (string) - Description of the error. ### Response Example ```json { "success": true, "data": "1.260327.0" } ``` ``` -------------------------------- ### Override system DNS resolver Source: https://context7.com/xtls/libxray/llms.txt Replaces `net.DefaultResolver` so Go's DNS queries bypass the TUN interface. On Android, socket protection is applied; on Linux, interface binding is used. Use `ResetDns` to restore defaults. ```go // Android: protect the DNS socket via the controller callback dns.InitDns("8.8.8.8:53", func(fd uintptr) { vpnService.Protect(int(fd)) }) // Linux: bind DNS socket to a specific network interface dns.InitDns("8.8.8.8:53", "eth0") // Restore default resolver (e.g. when VPN stops) dns.ResetDns() ``` -------------------------------- ### ConvertXrayJsonToShareLinks Source: https://context7.com/xtls/libxray/llms.txt Serializes an Xray JSON configuration back into shareable links. Each outbound configuration is converted into its canonical URI format. ```APIDOC ## ConvertXrayJsonToShareLinks ### Description Serializes an Xray JSON config back to share links. Each outbound in the Xray config is serialized to its canonical URI. VMess outbounds produce VMessAEAD links. The outbound's `sendThrough` field is used as the link name/fragment. ### Method `libXray.ConvertXrayJsonToShareLinks(encodedXrayJson string)` ### Parameters * `encodedXrayJson` (string) - Base64 encoded Xray JSON configuration. ### Response Example ``` {"success":true,"data":"vless://xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx@example.com:443?flow=xtls-rprx-vision&...#MyServer"} ``` ``` -------------------------------- ### InitDns / ResetDns Source: https://context7.com/xtls/libxray/llms.txt Initializes or resets the DNS resolver. On Android and Linux, this can override the system's default DNS resolver to bypass the TUN interface or bind to a specific interface. ```APIDOC ## InitDns / ResetDns ### Description Overrides the system DNS resolver. Replaces `net.DefaultResolver` so that Go's DNS queries bypass the TUN interface and go directly to the specified server (with socket protection applied on Android, or interface binding on Linux). ### Method `dns.InitDns(server string, callback interface{}) `dns.ResetDns() ### Parameters * `server` (string) - The DNS server address and port (e.g., `"8.8.8.8:53"`). * `callback` (interface{}) - Optional. On Android, this is a function to protect the DNS socket (`func(fd uintptr)`). On Linux, this can be the network interface name (string). ### Usage Examples ```go // Android: protect the DNS socket via the controller callback dns.InitDns("8.8.8.8:53", func(fd uintptr) { vpnService.Protect(int(fd)) }) // Linux: bind DNS socket to a specific network interface dns.InitDns("8.8.8.8:53", "eth0") // Restore default resolver (e.g. when VPN stops) dns.ResetDns() ``` ``` -------------------------------- ### StopXray Source: https://context7.com/xtls/libxray/llms.txt Stops the running Xray instance, closes the core server, and releases all resources. This function is safe to call even if no Xray instance is currently running. ```APIDOC ## StopXray ### Description Stops the running Xray instance, closes the core server, and releases all resources. This function is safe to call even if no Xray instance is currently running. ### Method libXray.StopXray ### Request Example ```go result := libXray.StopXray() // Base64-encoded JSON: {"success":true} decoded, _ := base64.StdEncoding.DecodeString(result) fmt.Println(string(decoded)) // {"success":true} ``` ### Response #### Success Response (200) - **success** (bool) - Indicates if the operation was successful. #### Error Response - **success** (bool) - Always false. - **error** (string) - Description of the error. ### Response Example ```json { "success": true } ``` ``` -------------------------------- ### GetFreePorts Source: https://context7.com/xtls/libxray/llms.txt Requests a specified number of available TCP ports from the operating system's kernel. ```APIDOC ## GetFreePorts ### Description Asks the kernel for N available TCP ports. Returns a list of currently free ports. Useful for dynamically assigning inbound ports to Xray listeners before writing the config file. ### Method `libXray.GetFreePorts(count int)` ### Parameters * `count` (int) - The number of free ports to request. ### Response Example ``` {"success":true,"data":{"ports":[51234,51235,51236]}} ``` ``` -------------------------------- ### ReadGeoFiles Source: https://context7.com/xtls/libxray/llms.txt Scans an Xray configuration to identify and return a list of all `.dat` geo filenames referenced in routing rules and DNS settings. ```APIDOC ## ReadGeoFiles ### Description Extracts geo file names referenced in an Xray config. Scans routing rules and DNS server entries in the config for `geosite:` and `geoip:` (and `ext:` custom) references and returns the list of `.dat` filenames actually used. ### Method `libXray.ReadGeoFiles(encodedXrayConfig string)` ### Parameters * `encodedXrayConfig` (string) - Base64 encoded Xray configuration file content. ### Response Example ``` {"success":true,"data":{"domain":["geosite.dat"],"ip":["geoip.dat","custom.dat"]}} ``` ``` -------------------------------- ### Stop Xray Instance Source: https://context7.com/xtls/libxray/llms.txt Stops the currently running Xray instance and releases associated resources. This function is safe to call even if no Xray instance is active. ```go result := libXray.StopXray() // Base64-encoded JSON: {"success":true} decoded, _ := base64.StdEncoding.DecodeString(result) fmt.Println(string(decoded)) // {"success":true} ``` -------------------------------- ### Unified Base64-encoded JSON response Source: https://context7.com/xtls/libxray/llms.txt The `CallResponse[T]` structure serves as a unified response envelope for all wrapper functions in libXray. Responses are Base64 encoded JSON strings that can be decoded to check for success, retrieve data, or view error messages. ```APIDOC ## `CallResponse[T]` — Unified Base64-encoded JSON response Every wrapper function returns a Base64 string that decodes to this structure. The helper `EncodeToBase64` is called internally by all wrappers. ### Go Decode Example ```go import ( "encoding/base64" "encoding/json" "fmt" "github.com/xtls/libxray/nodep" ) // Decode any libXray response generically func decodeResponse(b64Result string) { raw, err := base64.StdEncoding.DecodeString(b64Result) if err != nil { panic(err) } var resp struct { Success bool `json:"success"` Data json.RawMessage `json:"data,omitempty"` Err string `json:"error,omitempty"` } json.Unmarshal(raw, &resp) if resp.Success { fmt.Println("OK, data:", string(resp.Data)) } else { fmt.Println("Error:", resp.Err) } } // Using the typed helper directly in library code: var response nodep.CallResponse[int64] encoded := response.EncodeToBase64(int64(342), nil) // encoded → base64({"success":true,"data":342}) ``` ```