### Run Go Examples Source: https://github.com/51degrees/device-detection-go/blob/main/examples/README.md Commands to run the example programs from the examples directory. Use the appropriate subdirectory (dd or onpremise) for the example directory, or run the web and uach examples directly. ```bash go run ./examples/[dd/onpremise]/example_dir go run ./examples/web go run ./examples/uach ``` -------------------------------- ### Run update_polling_interval example Source: https://github.com/51degrees/device-detection-go/blob/main/examples/onpremise/README.md Command to run the update_polling_interval example, which demonstrates periodic data file updates by polling the 51degrees distributor server or a custom URL. Requires a license key environment variable. ```bash LICENSE_KEY=my_license_key go run onpremise/update_polling_interval.go ``` -------------------------------- ### Example: basic engine creation and processing Source: https://github.com/51degrees/device-detection-go Shows how to create an engine with a data file and auto-update disabled, process evidence (User-Agent header), and free results. Requires a valid data file path; errors are fatal in this example. ```go engine, err := onpremise.New( onpremise.WithDataFile("51Degrees-LiteV4.1.hash"), onpremise.WithAutoUpdate(false), ) if err != nil { log.Fatalf("failed to create engine: %v", err) } defer engine.Stop() results, err := engine.Process([]onpremise.Evidence{ {Prefix: dd.HttpHeaderString, Key: "User-Agent", Value: ua}, }) if err != nil { log.Fatalf("detection failed: %v", err) } defer results.Free() ``` -------------------------------- ### Process evidence with e.Process Source: https://github.com/51degrees/device-detection-go/blob/main/examples/onpremise/README.md Processes a list of evidence headers to perform device detection. The example uses Sec-Ch-Ua-Arch and Sec-Ch-Ua-Model headers. ```go resultsHash, err := e.Process( []Evidence{ { Prefix: dd.HttpHeaderString, Key: "Sec-Ch-Ua-Arch", Value: "x86", }, { Prefix: dd.HttpHeaderString, Key: "Sec-Ch-Ua-Model", Value: "Intel", }, } ) ``` -------------------------------- ### Fetch assets with pwsh ci/fetch-assets.ps1 Source: https://github.com/51degrees/device-detection-go/blob/main/examples/README.md Run from the repository root to download the required data file and example evidence. Alternatively, download the files manually from the device-detection-data repo. ```powershell pwsh ci/fetch-assets.ps1 . ``` -------------------------------- ### Example metrics printing Source: https://github.com/51degrees/device-detection-go Example of printing match metrics: iterations, drift, difference, and method. ```go fmt.Printf("iterations: %d, drift: %d, difference: %d, method: %v\n", results.Iterations(), results.Drift(), results.Difference(), results.Method()) ``` -------------------------------- ### Create engine with New Source: https://github.com/51degrees/device-detection-go/blob/main/examples/onpremise/README.md Creates an engine with a hash config, a custom data update URL, and an existing data file. ```go e, err := New( WithConfigHash(config), WithDataUpdateUrl("datafileUrl.com/myFile.gz"), WithDataFile("51Degrees-LiteV4.1.hash"), ) ``` -------------------------------- ### WithLogging option Source: https://github.com/51degrees/device-detection-go/blob/main/examples/onpremise/README.md Enables or disables the logger. Enable is true or false. ```go WithLogging(enabled bool) EngineOptions ``` -------------------------------- ### WithDataFile option Source: https://github.com/51degrees/device-detection-go/blob/main/examples/onpremise/README.md Provides an existing datafile. Required option. Path is the path to the datafile. ```go WithDataFile(path string) EngineOptions ``` -------------------------------- ### Set CGO_ENABLED environment variable Source: https://github.com/51degrees/device-detection-go/blob/main/examples/README.md Required on Windows to enable CGO, which is necessary for using the C-based device detection engine. Set to 1 before building or running examples. ```go go env -w CGO_ENABLED=1 ``` -------------------------------- ### WithProduct option Source: https://github.com/51degrees/device-detection-go/blob/main/examples/onpremise/README.md Sets the product to use when pulling the data file. Only usable with the default 51Degrees data file URL; appended as a query parameter. ```go WithProduct(product string) EngineOptions ``` -------------------------------- ### Get values with resultsHash.ValuesString Source: https://github.com/51degrees/device-detection-go/blob/main/examples/onpremise/README.md Retrieves the BrowserName property from the results. Logs a fatal error if retrieval fails. ```go browser, err := resultsHash.ValuesString("BrowserName", ",") if err != nil { log.Fatalf("Failed to get BrowserName: %v", err) } ``` -------------------------------- ### NewConfigHash usage example Source: https://github.com/51degrees/device-detection-go Shows how to create a ConfigHash with high performance, set concurrency and difference, and initialize a resource manager from a file. The config is passed by pointer to InitManagerFromFile. ```go config := dd.NewConfigHash(dd.HighPerformance) config.SetConcurrency(12) config.SetDifference(12500) manager := dd.NewResourceManager() err := dd.InitManagerFromFile(manager, *config, "", filePath) ``` -------------------------------- ### WithCustomLogger option Source: https://github.com/51degrees/device-detection-go/blob/main/examples/onpremise/README.md Provides a custom logger. The logger must implement the LogWriter interface. ```go WithCustomLogger(logger LogWriter) EngineOptions ``` -------------------------------- ### WithDataUpdateUrl option Source: https://github.com/51degrees/device-detection-go/blob/main/examples/onpremise/README.md Provides the datafile update URL. URL is the URL to the datafile. ```go WithDataUpdateUrl(url string) EngineOptions ``` -------------------------------- ### Free memory with resultsHash.Free Source: https://github.com/51degrees/device-detection-go/blob/main/examples/onpremise/README.md Defer freeing the results hash to release memory. ```go defer resultsHash.Free() ``` -------------------------------- ### GetFilePath example: multiple names and absolute directory Source: https://github.com/51degrees/device-detection-go Example using multiple candidate names and an absolute directory. It checks for fs.ErrNotExist to log when no data file is found. ```go // Multiple candidate names, absolute directory, error handling. path, err := dd.GetFilePath("/var/data", []string{"Lite.hash", "lite-v4.hash"}) if err != nil { if errors.Is(err, fs.ErrNotExist) { log.Println("no data file found under /var/data") } } ``` -------------------------------- ### Full onpremise.Engine configuration with all options Source: https://github.com/51degrees/device-detection-go Constructs an onpremise.Engine with all available options, including data file, config hash, properties, license key, product, polling interval, randomization, retries, file watch, temp data copy, temp data dir, update on start, auto update, and logging. Requires a valid data file path and license key; on error, logs fatal and stops the engine. ```go engine, err := onpremise.New( onpremise.WithDataFile("51Degrees-LiteV4.1.hash"), onpremise.WithConfigHash(dd.NewConfigHash(dd.Balanced)), onpremise.WithProperties([]string{"IsMobile", "BrowserName", "PlatformName"}), onpremise.WithLicenseKey("YOUR_LICENSE_KEY"), onpremise.WithProduct("V4TAC"), onpremise.WithPollingInterval(3600), // 1 hour onpremise.WithRandomization(120), // ±2 min jitter onpremise.WithMaxRetries(3), onpremise.WithFileWatch(true), onpremise.WithTempDataCopy(true), onpremise.WithTempDataDir("/var/tmp/51d"), onpremise.WithUpdateOnStart(true), onpremise.WithAutoUpdate(true), onpremise.WithLogging(true), ) if err != nil { log.Fatalf("failed to build engine: %v", err) } defer engine.Stop() ``` -------------------------------- ### WithLicenseKey option Source: https://github.com/51degrees/device-detection-go/blob/main/examples/onpremise/README.md Sets the license key to use when pulling the data file. Only usable with the default 51Degrees data file URL; appended as a query parameter. ```go WithLicenseKey(key string) EngineOptions ``` -------------------------------- ### Create config with dd.NewConfigHash Source: https://github.com/51degrees/device-detection-go/blob/main/examples/onpremise/README.md Creates a hash config with the Balanced profile. Possible profiles include Default, LowMemory, BalancedTemp, Balanced, HighPerformance, and InMemory. ```go config := dd.NewConfigHash(dd.Balanced) ``` -------------------------------- ### WithProperties option Source: https://github.com/51degrees/device-detection-go/blob/main/examples/onpremise/README.md Sets which properties are checked. Default is an empty array (all properties will be checked). ```go WithProperties(properties []string) EngineOptions ``` -------------------------------- ### SizeManagerFromFile usage example Source: https://github.com/51degrees/device-detection-go Example of calling SizeManagerFromFile with properties "IsMobile" and a data file path. On error, it logs a fatal message; otherwise it prints the required memory size in bytes. ```go config := dd.NewConfigHash(dd.Balanced) size, err := config.SizeManagerFromFile("IsMobile", "51Degrees-LiteV4.1.hash") if err != nil { log.Fatalf("failed to compute size: %v", err) } fmt.Printf("manager needs %d bytes\n", size) ``` -------------------------------- ### WithConfigHash option Source: https://github.com/51degrees/device-detection-go/blob/main/examples/onpremise/README.md Sets the config for the hash matching algorithm. Default is Balanced profile. Possible profiles: Default, LowMemory, BalancedTemp, Balanced, HighPerformance, InMemory. ```go WithConfigHash(configHash *dd.ConfigHash) EngineOptions ``` -------------------------------- ### New Source: https://github.com/51degrees/device-detection-go/blob/main/examples/onpremise/README.md Creates a new onpremise engine with the provided options. This is the main entry point for device detection and automatic data file updates. ```APIDOC ## New ### Description Creates a new onpremise engine with the provided options. ### Method New ### Parameters #### Options - **WithConfigHash** (configHash *dd.ConfigHash) - Optional - Sets config for hash matching algorithm. Default is Balanced profile. Possible profiles: Default, LowMemory, BalancedTemp, Balanced, HighPerformance, InMemory. - **WithDataFile** (path string) - Required - Provides existing datafile path. - **WithDataUpdateUrl** (url string) - Optional - Provides datafile update URL. - **WithPollingInterval** (seconds int) - Optional - Polling interval in seconds for data file fetching. - **WithRandomizationSeed** (seed int) - Optional - Randomization seed for data file fetching. - **WithLogging** (enabled bool) - Optional - Enables or disables logger. - **WithCustomLogger** (logger LogWriter) - Optional - Provides custom logger; must implement LogWriter interface. - **WithProduct** (product string) - Optional - Sets product to use when pulling data file (only with default URL). - **WithLicenseKey** (key string) - Optional - Sets license key to use when pulling data file (only with default URL). - **WithFileWatch** (enabled bool) - Optional - Enables or disables file watching; default true. - **WithAutoUpdate** (enabled bool) - Optional - Enables or disables auto update; default true. - **WithTempDataCopy** (enabled bool) - Optional - Enables or disables creating a temp copy of data file; default true. - **WithProperties** (properties []string) - Optional - Sets which properties to check; default empty array (all properties). - **SetTempDataDir** (dir string) - Optional - Sets directory for temp data file; default system temp. ### Response Returns an engine instance and an error. ### Example ```go e, err := New( WithConfigHash(config), WithDataUpdateUrl("datafileUrl.com/myFile.gz"), WithDataFile("51Degrees-LiteV4.1.hash"), ) ``` ``` -------------------------------- ### SetTempDataDir option Source: https://github.com/51degrees/device-detection-go/blob/main/examples/onpremise/README.md Sets the directory to store the temp data file. Default is the system temp directory. ```go SetTempDataDir(dir string) EngineOptions ``` -------------------------------- ### Hot reload from file example Source: https://github.com/51degrees/device-detection-go Example of hot reloading the data file while serving detection requests. The loop sleeps 5 seconds, then calls ReloadFromFile with the new data file path, logging success or failure. ```go // Serve detection requests while the data file is swapped underneath. for { time.Sleep(5 * time.Second) if err := manager.ReloadFromFile(newDataFilePath); err != nil { log.Printf("reload failed: %v", err) } else { log.Println("data file reloaded") } } ``` -------------------------------- ### Process Source: https://github.com/51degrees/device-detection-go/blob/main/examples/onpremise/README.md Processes evidence to perform device detection. Takes a slice of Evidence and returns a results object with detection results. ```APIDOC ## Process ### Description Processes evidence to perform device detection. ### Method Process ### Parameters #### Request Body - **evidence** ([]Evidence) - Required - List of evidence items, each with Prefix, Key, and Value. ### Response Returns a results object and an error. ### Example ```go resultsHash, err := e.Process( []Evidence{ { Prefix: dd.HttpHeaderString, Key: "Sec-Ch-Ua-Arch", Value: "x86", }, { Prefix: dd.HttpHeaderString, Key: "Sec-Ch-Ua-Model", Value: "Intel", }, } ) ``` ``` -------------------------------- ### InitManagerFromFile usage example Source: https://github.com/51degrees/device-detection-go Shows how to initialize a ResourceManager from a .hash data file. Requires a ResourceManager created with NewResourceManager and a ConfigHash from NewConfigHash. The properties string is comma-separated, e.g. "IsMobile,BrowserName"; an empty string requests the data file's default set. The filePath points to the .hash data file. ```go manager := dd.NewResourceManager() defer manager.Free() config := dd.NewConfigHash(dd.Balanced) err := dd.InitManagerFromFile(manager, *config, "IsMobile,BrowserName", "51Degrees-LiteV4.1.hash") if err != nil { log.Fatalf("Failed to initialize resource manager: %v", err) } ``` -------------------------------- ### ValuesString Example Source: https://github.com/51degrees/device-detection-go Example usage of ValuesString to read the IsMobile property value, handling errors and printing the result. ```go value, err := results.ValuesString("IsMobile", ",") if err != nil { log.Fatalf("failed to read value: %v", err) } fmt.Println("IsMobile:", value) ``` -------------------------------- ### WithRandomizationSeed option Source: https://github.com/51degrees/device-detection-go/blob/main/examples/onpremise/README.md Provides randomization of seconds for data file fetching. Seed is the randomization seed. ```go WithRandomizationSeed(seconds int) EngineOptions ``` -------------------------------- ### Create ResultsHash and defer Free Source: https://github.com/51degrees/device-detection-go Example of creating a ResultsHash with manager, capacity 1, and overrides 0, then deferring Free(). ```go results := dd.NewResultsHash(manager, 1, 0) defer results.Free() ``` -------------------------------- ### Example: SetResponseHeaders in UACH flow Source: https://github.com/51degrees/device-detection-go Example from examples/uach/uach.go:290 showing how to set response headers such as Accept-CH listing additional client hints the engine needs, derived from SetHeader...Accept-CH properties. Uses dd.NewResultsHash and dd.NewEvidenceHash, copies request headers into evidence, matches evidence, then calls SetResponseHeaders and logs any error. ```go func handler(w http.ResponseWriter, r *http.Request) { results := dd.NewResultsHash(manager, 1, 0) defer results.Free() evidence := dd.NewEvidenceHash(1) defer evidence.Free() // ... copy request headers (User-Agent, Sec-CH-UA-*, ...) into evidence ... _ = results.MatchEvidence(evidence) // Sets headers such as Accept-CH listing the additional client hints // the engine needs, derived from SetHeader...Accept-CH properties. if err := results.SetResponseHeaders(w, manager); err != nil { log.Printf("failed to set response headers: %v", err) } } ``` -------------------------------- ### Free Source: https://github.com/51degrees/device-detection-go/blob/main/examples/onpremise/README.md Frees memory allocated for the results. Must be called to avoid memory leaks. ```APIDOC ## Free ### Description Frees memory allocated for the results. ### Method Free ### Parameters None ### Response None ### Example ```go defer resultsHash.Free() ``` ``` -------------------------------- ### GetFilePath example: find lite data file Source: https://github.com/51degrees/device-detection-go Example usage of GetFilePath to find the lite data file by searching two levels up from the working directory and all subdirectories. It imports the dd package and handles errors with log.Fatalf. ```go import "github.com/51Degrees/device-detection-go/v4/dd" // Find the lite data file by searching two levels up from the working // directory and all its subdirectories. filePath, err := dd.GetFilePath("../..", []string{"51Degrees-LiteV4.1.hash"}) if err != nil { log.Fatalf("Could not find the data file: %v", err) } ``` -------------------------------- ### Stop method example Source: https://github.com/51degrees/device-detection-go Creates an engine with a data file and disables auto-update, then defers Stop to release C resources. ```go engine, err := onpremise.New(onpremise.WithDataFile("51Degrees-LiteV4.1.hash"), onpremise.WithAutoUpdate(false)) if err != nil { log.Fatal(err) } defer engine.Stop() // release the C resources ``` -------------------------------- ### WithPollingInterval option Source: https://github.com/51degrees/device-detection-go/blob/main/examples/onpremise/README.md Provides the polling interval for data file fetching. Seconds is the polling interval in seconds. ```go WithPollingInterval(seconds int) EngineOptions ``` -------------------------------- ### Match by User-Agent then re-match by device id Source: https://github.com/51degrees/device-detection-go Example showing detection by User-Agent, retrieving the device id, then re-matching with a new ResultsHash using MatchDeviceId. Includes error handling for device id retrieval and device-id match. ```go r1 := dd.NewResultsHash(manager, 1, 0) defer r1.Free() _ = r1.MatchUserAgent(ua) deviceId, err := r1.DeviceId() if err != nil { log.Fatalf("failed to get device id: %v", err) } r2 := dd.NewResultsHash(manager, 1, 0) defer r2.Free() if err := r2.MatchDeviceId(deviceId); err != nil { log.Fatalf("device-id match failed: %v", err) } ``` -------------------------------- ### Process method example Source: https://github.com/51degrees/device-detection-go Processes HTTP header evidence to detect device properties like IsMobile. The results must be freed with defer results.Free(). ```go results, err := engine.Process([]onpremise.Evidence{ {Prefix: dd.HttpHeaderString, Key: "User-Agent", Value: ua}, {Prefix: dd.HttpHeaderString, Key: "Sec-CH-UA-Mobile", Value: "?1"}, }) if err != nil { log.Printf("detection failed: %v", err) return } defer results.Free() if has, _ := results.HasValues("IsMobile"); has { val, _ := results.ValuesString("IsMobile", ",") fmt.Println("IsMobile:", val) } ``` -------------------------------- ### WithAutoUpdate option Source: https://github.com/51degrees/device-detection-go/blob/main/examples/onpremise/README.md Enables or disables auto update. Default is true. If enabled, the engine automatically pulls the data file from the distributor; if disabled, options like WithDataUpdateUrl and WithLicenseKey are ignored. ```go WithAutoUpdate(enabled bool) EngineOptions ``` -------------------------------- ### WithUpdateOnStart Source: https://github.com/51degrees/device-detection-go Enables or disables update on start for the Engine. This option is applied during construction. ```APIDOC ## WithUpdateOnStart ### Description Enables or disables update on start for the Engine. ### Signature ```go func WithUpdateOnStart(enabled bool) EngineOptions ``` ``` -------------------------------- ### WithFileWatch option Source: https://github.com/51degrees/device-detection-go/blob/main/examples/onpremise/README.md Enables or disables file watching. If a third party updates the data file on the file system, the engine will automatically reload it. Default is true. ```go WithFileWatch(enabled bool) EngineOptions ``` -------------------------------- ### GetHttpHeaderKeys example for web application Source: https://github.com/51degrees/device-detection-go Builds an evidence list from HTTP request headers using the keys returned by GetHttpHeaderKeys, then processes it. ```go keys := engine.GetHttpHeaderKeys() evidenceList := make([]onpremise.Evidence, 0, len(keys)) for _, k := range keys { if v := r.Header.Get(k.Key); v != "" { evidenceList = append(evidenceList, onpremise.Evidence{Prefix: k.Prefix, Key: k.Key, Value: v}) } } results, err := engine.Process(evidenceList) ``` -------------------------------- ### WithTempDataCopy option Source: https://github.com/51degrees/device-detection-go/blob/main/examples/onpremise/README.md Enables or disables creating a temp copy of the data file. Default is true. If enabled, the engine creates a temp copy and uses it to initialize the manager; if disabled, it uses the original data file. Useful when a third party updates the data file on the file system. ```go WithTempDataCopy(enabled bool) EngineOptions ``` -------------------------------- ### Check error from MatchUserAgent Source: https://github.com/51degrees/device-detection-go Check the returned error and log/abort on failure. This pattern is used in examples to handle C exception translation errors. ```go err := results.MatchUserAgent(ua) if err != nil { log.Fatalf("Failed to perform detection: %v", err) } ``` -------------------------------- ### Evidence-based matching with error handling Source: https://github.com/51degrees/device-detection-go Example of creating an EvidenceHash, adding User-Agent and Sec-CH-UA-Mobile headers, then matching evidence with error handling as done by the engine. ```go ev := dd.NewEvidenceHash(1) defer ev.Free() _ = ev.Add(dd.HttpHeaderString, "User-Agent", ua) _ = ev.Add(dd.HttpHeaderString, "Sec-CH-UA-Mobile", "?1") results := dd.NewResultsHash(manager, 1, 0) defer results.Free() if err := results.MatchEvidence(ev); err != nil { log.Printf("detection failed: %v", err) } ``` -------------------------------- ### GetPublishedDate usage example Source: https://github.com/51degrees/device-detection-go Prints the data file's publication date formatted as YYYY-MM-DD. The onpremise.Engine uses this internally to log the date after each reload. ```go published := dd.GetPublishedDate(manager) fmt.Printf("Data file published on: %s\n", published.Format("2006-01-02")) ``` -------------------------------- ### onpremise.New Source: https://github.com/51degrees/device-detection-go Constructs a new on-premise Engine with the provided options. All options are applied in the order passed to onpremise.New. Returns an error if required options are missing or invalid. ```APIDOC ## onpremise.New ### Description Constructs a new on-premise Engine with the provided options. All options are applied in the order passed to onpremise.New. Returns an error if required options are missing or invalid. ### Method New ### Parameters #### Options - **WithDataFile** (path string) - Required - Path to the local `.hash` data file; validated with `os.Stat`. Error `ErrNoDataFileProvided` if absent. - **WithConfigHash** (configHash *dd.ConfigHash) - Optional - Configures the hash matching algorithm. Default: `dd.NewConfigHash(dd.Balanced)`. - **WithLicenseKey** (key string) - Optional - License key for the 51Degrees distributor; only allowed with the default data file URL; appended as the `LicenseKeys` query parameter. - **WithProduct** (product string) - Optional - Distributor product; only allowed with the default data file URL; appended as the `Product` query parameter. Requires `WithLicenseKey`. - **WithDataUpdateUrl** (urlStr string) - Optional - Custom URL to download the data file from; validated with `url.ParseRequestURI`. Default: `https://distributor.51degrees.com/api/v2/download?Type=HashV41&Download=True&Product=V4TAC`. - **WithMaxRetries** (retries int) - Optional - Maximum number of retries to pull the data file if a request fails. Default per `FileUpdater`. - **WithPollingInterval** (seconds int) - Optional - Interval in seconds to pull the data file (converted to milliseconds via `SetDataFilePullEveryMs(seconds * 1000)`). Default per `FileUpdater`. - **WithLogging** (enabled bool) - Optional - Enables or disables the logger. Default per `FileUpdater`. - **WithCustomLogger** (logger common_go.LogWriter) - Optional - Sets a custom logger. Default per `FileUpdater`. - **WithFileWatch** (enabled bool) - Optional - Enables or disables the file watcher that reloads the data file when a 3rd party changes it. Default: `true`. - **WithUpdateOnStart** (enabled bool) - Optional - If enabled, pull the data file from distributor/custom URL once at initialization. Default: `false`. - **WithAutoUpdate** (enabled bool) - Optional - If enabled, automatically pull the data file from distributor/custom URL on the polling interval. When disabled, `WithDataUpdateUrl`/`WithLicenseKey` are ignored. Default: `true`. - **WithTempDataCopy** (enabled bool) - Optional - If enabled, create a temp copy of the data file and detect against it rather than the original file. Default: `true`. - **WithTempDataDir** (dir string) - Optional - Directory to store the temp data file; must exist and be a directory, else an error is returned. Default: system temp directory. - **WithRandomization** (seconds int) - Optional - Randomization time in seconds added to the pull interval when scheduling file pulls (converted to ms via `SetRandomization(seconds * 1000)`); avoids multiple engines pulling simultaneously. Default: `600` (10 minutes). - **WithProperties** (properties []string) - Optional - Comma-separated list of manager properties derived from the slice (joined with `","`), e.g. `["IsMobile","BrowserName"]`. `nil` leaves the default. Default: empty string (data file's default property set). ### Response #### Success Response Returns an `*Engine` and `error`. The engine is ready for use; call `engine.Stop()` when done. ### Request Example ```go engine, err := onpremise.New( onpremise.WithDataFile("51Degrees-LiteV4.1.hash"), onpremise.WithConfigHash(dd.NewConfigHash(dd.Balanced)), onpremise.WithProperties([]string{"IsMobile", "BrowserName", "PlatformName"}), onpremise.WithLicenseKey("YOUR_LICENSE_KEY"), onpremise.WithProduct("V4TAC"), onpremise.WithPollingInterval(3600), // 1 hour onpremise.WithRandomization(120), // ±2 min jitter onpremise.WithMaxRetries(3), onpremise.WithFileWatch(true), onpremise.WithTempDataCopy(true), onpremise.WithTempDataDir("/var/tmp/51d"), onpremise.WithUpdateOnStart(true), onpremise.WithAutoUpdate(true), onpremise.WithLogging(true), ) if err != nil { log.Fatalf("failed to build engine: %v", err) } defer engine.Stop() ``` ``` -------------------------------- ### Create dd.ConfigHash with HighPerformance profile and set options Source: https://github.com/51degrees/device-detection-go Creates a hash matching configuration using dd.NewConfigHash with the HighPerformance profile, then sets concurrency to 16 and enables the performance graph. The performance profile is the base configuration; setters adjust it on top. ```go config := dd.NewConfigHash(dd.HighPerformance) config.SetConcurrency(16) config.SetUsePerformanceGraph(true) ``` -------------------------------- ### Display package APIs with go doc Source: https://github.com/51degrees/device-detection-go/blob/main/README.md Shows all APIs, structures, and descriptions for the current package. Run from the dd or onpremise directory. ```bash go doc -all ``` -------------------------------- ### Full lifecycle: create manager, init from file, match user agent Source: https://github.com/51degrees/device-detection-go Shows the complete ResourceManager workflow: create with dd.NewResourceManager(), defer Free(), configure with dd.NewConfigHash(dd.Balanced), locate the data file via dd.GetFilePath, initialize with dd.InitManagerFromFile, inspect required HTTP headers via manager.HttpHeaderKeys, then reuse the manager for detections with dd.NewResultsHash and results.MatchUserAgent. Requires a valid data file path and the 51Degrees-LiteV4.1.hash file. ```go manager := dd.NewResourceManager() defer manager.Free() config := dd.NewConfigHash(dd.Balanced) filePath, err := dd.GetFilePath("../..", []string{"51Degrees-LiteV4.1.hash"}) if err != nil { log.Fatalf("data file not found: %v", err) } if err := dd.InitManagerFromFile(manager, *config, "IsMobile,BrowserName", filePath); err != nil { log.Fatalf("failed to init: %v", err) } // Manager now knows which HTTP headers the engine needs: for _, key := range manager.HttpHeaderKeys { fmt.Printf("evidence key: prefix=%d key=%s\n", key.Prefix, key.Key) } // Reuse the manager for many detections. results := dd.NewResultsHash(manager, 1, 0) defer results.Free() _ = results.MatchUserAgent(uaString) ``` -------------------------------- ### Run unit tests Source: https://github.com/51degrees/device-detection-go/blob/main/README.md Runs all unit tests from the root directory. ```bash go test ./... ``` -------------------------------- ### cgo build flags (dd/cgoflags.go) Source: https://github.com/51degrees/device-detection-go Centralized cgo flags so go build picks them up automatically. -fcommon allows common symbols, -lm links the math library, and -latomic (non-darwin) links libatomic for 32-bit atomic operations. ```go /* #cgo CFLAGS: -fcommon #cgo LDFLAGS: -lm #cgo !darwin LDFLAGS: -latomic */ ``` -------------------------------- ### New Source: https://github.com/51degrees/device-detection-go Creates an instance of the on-premise device detection engine. It requires a data file via WithDataFile and returns a running engine or an error. ```APIDOC ## New ### Description Creates an instance of the on-premise device detection engine. It requires a data file via WithDataFile and returns a running engine or an error. ### Function Signature ```go func New(opts ...EngineOptions) (*Engine, error) ``` ### Parameters - `opts` (`...EngineOptions`) - Optional - Zero or more option functions. ### Returns - `(*Engine, error)` - A running engine and an error. On error, the engine is stopped and nil is returned. ### Errors - `common_go.ErrNoDataFileProvided` - No WithDataFile option was supplied. - `common_go.ErrLicenseKeyRequired` - Default distributor URL used, auto-update enabled, and no license key/distributor params set. - Wrapped initialization errors - e.g., temp data copy creation, file reload, URL validation, watcher startup. - Option errors - Any error returned by an EngineOptions function. ### Request Example ```go engine, err := onpremise.New( onpremise.WithDataFile("51Degrees-LiteV4.1.hash"), onpremise.WithAutoUpdate(false), ) if err != nil { log.Fatalf("failed to create engine: %v", err) } defer engine.Stop() results, err := engine.Process([]onpremise.Evidence{ {Prefix: dd.HttpHeaderString, Key: "User-Agent", Value: ua}, }) if err != nil { log.Fatalf("detection failed: %v", err) } defer results.Free() ``` ``` -------------------------------- ### InitManagerFromFile function signature Source: https://github.com/51degrees/device-detection-go Initializes a ResourceManager from a hash-format data file on disk. Matches the C API fiftyoneDegreesHashInitManagerFromFile. On success, the manager's setHeaders map and HttpHeaderKeys field are populated for later use by ResultsHash.ResponseHeaders / ResultsHash.SetResponseHeaders. Returns an error if the C API reported an exception or a non-SUCCESS status code. ```go func InitManagerFromFile( manager *ResourceManager, config ConfigHash, properties string, filePath string) error ``` -------------------------------- ### InitManagerFromFile Source: https://github.com/51degrees/device-detection-go Initializes a ResourceManager from a hash-format data file on disk. Matches the C API fiftyoneDegreesHashInitManagerFromFile. Returns an error if the C API reported an exception or a non-SUCCESS status code. ```APIDOC ## InitManagerFromFile ### Description Initializes a `ResourceManager` from a hash-format data file on disk. Matches the C API `fiftyoneDegreesHashInitManagerFromFile`. ### Method Function ### Signature ```go func InitManagerFromFile( manager *ResourceManager, config ConfigHash, properties string, filePath string) error ``` ### Parameters - **manager** (`*ResourceManager`) - Required - The resource manager to initialize (create with `NewResourceManager`). - **config** (`ConfigHash`) - Required - Hash detection configuration (see `NewConfigHash` in `dd/config_hash.go`). - **properties** (`string`) - Required - Comma-separated list of required properties, e.g. `"IsMobile,BrowserName"`. Empty string requests the data file's default set. - **filePath** (`string`) - Required - Path to the `.hash` data file. ### Returns - **error** - non-nil if the C API reported an exception or a non-`SUCCESS` status code; `nil` otherwise. ### Errors - Wrapped error containing the C exception message - The C API threw an exception (message taken from `ExceptionGetMessage`). - Wrapped error containing the C status message - The status code returned by the C API was not `SUCCESS` (message from `StatusGetMessage`). ### Request Example ```go manager := dd.NewResourceManager() defer manager.Free() config := dd.NewConfigHash(dd.Balanced) err := dd.InitManagerFromFile(manager, *config, "IsMobile,BrowserName", "51Degrees-LiteV4.1.hash") if err != nil { log.Fatalf("Failed to initialize resource manager: %v", err) } ``` ``` -------------------------------- ### Build evidence and match with NewEvidenceHash and MatchEvidence Source: https://github.com/51degrees/device-detection-go Creates an evidence hash with capacity 3, adds User-Agent, Profile, and Cookie evidence, then matches it against a results hash. The results hash is created with the manager and evidence count; MatchEvidence returns an error on failure. ```go evidence := dd.NewEvidenceHash(3) defer evidence.Free() _ = evidence.Add(dd.HttpHeaderString, "User-Agent", "Mozilla/5.0 (Linux; Android 10; K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.6422.72 Mobile Safari/537.36") _ = evidence.Add(dd.HttpEvidenceQuery, "Profile", "Mobile") _ = evidence.Add(dd.HttpEvidenceCookie, "session", "abc123") fmt.Printf("evidence count: %d\n", evidence.Count()) results := dd.NewResultsHash(manager, uint32(evidence.Count()), 0) defer results.Free() if err := results.MatchEvidence(evidence); err != nil { log.Fatalf("match failed: %v", err) } ``` -------------------------------- ### ValuesString Source: https://github.com/51degrees/device-detection-go Returns a string of all values produced by the last detection for a property, separated by the given separator. Internally starts with a 50-byte buffer and retries with exact size if needed. Matches the C API fiftyoneDegreesResultsHashGetValuesString. ```go func (results *ResultsHash) ValuesString( propertyName string, separator string) (value string, err error) ``` -------------------------------- ### Trace() Source: https://github.com/51degrees/device-detection-go Not implemented — always returns an empty string. Marked as TODO: To be implemented. ```APIDOC ## Trace() ### Description Not implemented — always returns an empty string. Marked as TODO: To be implemented. ### Method Trace ### Endpoint func (results *ResultsHash) Trace() string ### Response #### Success Response - **string** - Always empty string. ``` -------------------------------- ### ValuesString Source: https://github.com/51degrees/device-detection-go Returns a string of all values produced by the last detection for a property. Multiple values are separated by the given separator. Internally (valuesStringWithSize) it starts with a 50-byte buffer and, if the actual size is larger, retries with the exact required size (actualSize + 1 to include the null terminator). Matches the C API fiftyoneDegreesResultsHashGetValuesString. ```APIDOC ## ValuesString ### Description Returns a string of all values produced by the last detection for a property. Multiple values are separated by the given separator. Internally (valuesStringWithSize) it starts with a 50-byte buffer and, if the actual size is larger, retries with the exact required size (actualSize + 1 to include the null terminator). Matches the C API fiftyoneDegreesResultsHashGetValuesString. ### Method Function ### Signature ```go func (results *ResultsHash) ValuesString(propertyName string, separator string) (value string, err error) ``` ### Parameters - **propertyName** (string) - Required - Property name, e.g. "BrowserName". - **separator** (string) - Required - Separator between multiple values, e.g. ",". ### Returns - **value** (string) - the property value(s) - **err** (error) - C exception message on failure ### Request Example ```go value, err := results.ValuesString("IsMobile", ",") if err != nil { log.Fatalf("failed to read value: %v", err) } fmt.Println("IsMobile:", value) ``` ``` -------------------------------- ### Direct usage of Exception in application code Source: https://github.com/51degrees/device-detection-go Shows how application code can directly use Exception: create a new exception and check its initial state. The fresh exception is okay, so IsOkay returns true. ```go exp := dd.NewException() fmt.Println("fresh exception is okay:", exp.IsOkay()) // true exp.Clear() ``` -------------------------------- ### InitManagerFromMemory function stub Source: https://github.com/51degrees/device-detection-go Placeholder implementation that always returns nil without initializing the manager. Not implemented in this release; matches the C API fiftyoneDegreesHashInitManagerFromFile. ```go // TODO: To be implemeted func InitManagerFromMemory( manager *ResourceManager, config ConfigHash, properties string, memory unsafe.Pointer, size uint64) error { // TODO: To be implemented return nil } ``` -------------------------------- ### Values (Not Implemented) Source: https://github.com/51degrees/device-detection-go Not implemented in this release — always returns (nil, nil). ```go // TODO: To be implemeted func (results *ResultsHash) Values( requiredPropertyIndex int) (values []string, err error) { // TODO: To be implemented return nil, nil } ``` -------------------------------- ### Default data file URL constant (onpremise/onpremise.go) Source: https://github.com/51degrees/device-detection-go Unexported constant defining the default data file URL used by the engine. The URL is considered 'default' only when it exactly equals this value. ```go const defaultDataFileUrl = "https://distributor.51degrees.com/api/v2/download?Type=HashV41&Download=True&Product=V4TAC" ``` -------------------------------- ### InitManagerFromMemory Source: https://github.com/51degrees/device-detection-go Initializes a resource manager from data file content already loaded into contiguous memory. Note: Not implemented in this release; it always returns nil without performing any work. ```APIDOC ## InitManagerFromMemory ### Description Initializes a resource manager from data file content already loaded into contiguous memory. Note: Not implemented in this release; it always returns nil without performing any work. ### Function Signature ```go func InitManagerFromMemory( manager *ResourceManager, config ConfigHash, properties string, memory unsafe.Pointer, size uint64) error ``` ### Parameters - **manager** (*ResourceManager) - Required - An initialized resource manager. - **config** (ConfigHash) - Required - Configuration hash. - **properties** (string) - Required - Properties string. - **memory** (unsafe.Pointer) - Required - Pointer to contiguous memory containing data file content. - **size** (uint64) - Required - Size of the memory buffer. ### Returns - **error** - Always returns nil (no error) in this release. ``` -------------------------------- ### Free method signature Source: https://github.com/51degrees/device-detection-go Frees C resources: each tracked key/value C string and the C evidence array. Sets fields to nil, making the object idempotent. ```go func (evidence *Evidence) Free() ``` -------------------------------- ### WithDataFile Source: https://github.com/51degrees/device-detection-go Sets the path to the data file for the Engine. This option is applied during construction. ```APIDOC ## WithDataFile ### Description Sets the path to the data file for the Engine. ### Signature ```go func WithDataFile(path string) EngineOptions ``` ``` -------------------------------- ### TraceByIndex(index) Source: https://github.com/51degrees/device-detection-go Not implemented — always returns an empty string and nil error. ```APIDOC ## TraceByIndex(index) ### Description Not implemented — always returns an empty string and nil error. ### Method TraceByIndex ### Endpoint func (results *ResultsHash) TraceByIndex(index uint32) (string, error) ### Parameters #### Path Parameters - **index** (uint32) - Required - The index of the result. ### Response #### Success Response - **string** - Always empty string. - **error** - Always nil. ``` -------------------------------- ### WithProduct Source: https://github.com/51degrees/device-detection-go Sets the product for the Engine. This option is applied during construction. ```APIDOC ## WithProduct ### Description Sets the product for the Engine. ### Signature ```go func WithProduct(product string) EngineOptions ``` ``` -------------------------------- ### PropertyType (Not Implemented) Source: https://github.com/51degrees/device-detection-go Not implemented in this release — always returns nil. ```go // TODO: To be implemeted func (results *ResultsHash) PropertyType( requiredPropertyIndex int) reflect.Type { // TODO: To be implemented return nil } ``` -------------------------------- ### Package constant: defaultDataFileUrl Source: https://github.com/51degrees/device-detection-go Unexported constant defining the default data file URL pointing at the 51Degrees distributor service. When this exact URL is used with auto-update enabled, a license key and product are appended as query parameters. ```go const ( defaultDataFileUrl = "https://distributor.51degrees.com/api/v2/download?Type=HashV41&Download=True&Product=V4TAC" ) ``` -------------------------------- ### Difference() Source: https://github.com/51degrees/device-detection-go Returns the configured difference value. ```APIDOC ## Difference() ### Description Returns the configured difference value. ### Method Difference() ### Returns - **int32** - The configured difference value. ### Signature ```go func (config *ConfigHash) Difference() int32 ``` ``` -------------------------------- ### WithLicenseKey Source: https://github.com/51degrees/device-detection-go Sets the license key for the Engine. This option is applied during construction. ```APIDOC ## WithLicenseKey ### Description Sets the license key for the Engine. ### Signature ```go func WithLicenseKey(key string) EngineOptions ``` ``` -------------------------------- ### NewConfigHash constructor signature Source: https://github.com/51degrees/device-detection-go Creates a new ConfigHash with the given performance profile. Invalid values default to Default. Returns a non-nil pointer to a plain Go struct with no C heap memory, so no Free method or finalizer is needed. ```go func NewConfigHash(perf PerformanceProfile) *ConfigHash ``` -------------------------------- ### WithConfigHash Source: https://github.com/51degrees/device-detection-go Sets the configuration hash for the Engine. This option is applied during construction. ```APIDOC ## WithConfigHash ### Description Sets the configuration hash for the Engine. ### Signature ```go func WithConfigHash(configHash *dd.ConfigHash) EngineOptions ``` ``` -------------------------------- ### Error handling / lifecycle — finalizer panic protection Source: https://github.com/51degrees/device-detection-go Shows the required defer evidence.Free() call. Without it, the finalizer panics when garbage collection runs. ```go evidence := dd.NewEvidenceHash(1) _ = evidence.Add(dd.HttpHeaderString, "User-Agent", ua) defer evidence.Free() // MUST be called; without it the finalizer panics when GC runs ``` -------------------------------- ### WithProperties Source: https://github.com/51degrees/device-detection-go Sets the properties for the Engine. This option is applied during construction. ```APIDOC ## WithProperties ### Description Sets the properties for the Engine. ### Signature ```go func WithProperties(properties []string) EngineOptions ``` ``` -------------------------------- ### Free method signature Source: https://github.com/51degrees/device-detection-go Frees the C resources via C.ResultsHashFree and nulls CPtr. Idempotent. ```go func (results *ResultsHash) Free() ``` -------------------------------- ### Free method signature Source: https://github.com/51degrees/device-detection-go Frees the C string and sets CPtr to nil. Idempotent; a nil CPtr makes subsequent Properties() panic if called. ```go func (properties *PropertiesRequired) Free() ``` -------------------------------- ### Import dd package Source: https://github.com/51degrees/device-detection-go/blob/main/README.md Imports the lower-level dd package. The package is built automatically by CGo during go build. ```go import "github.com/51Degrees/device-detection-go/v4/dd" ``` -------------------------------- ### ConfigHash setter method signatures Source: https://github.com/51degrees/device-detection-go All setters write directly into the underlying C structure. They return no value and never return errors; invalid values are not validated in Go. ```go func (config *ConfigHash) SetDifference(diff int32) func (config *ConfigHash) SetDrift(drift int32) func (config *ConfigHash) SetUsePerformanceGraph(use bool) func (config *ConfigHash) SetUsePredictiveGraph(use bool) func (config *ConfigHash) SetConcurrency(concurrency uint16) func (config *ConfigHash) SetTraceRoute(trace bool) func (config *ConfigHash) SetUseUpperPrefixHeaders(use bool) func (config *ConfigHash) SetUpdateMatchedUserAgent(update bool) func (config *ConfigHash) SetAllowUnmatched(allow bool) ``` -------------------------------- ### Concurrency() Source: https://github.com/51degrees/device-detection-go Returns the configured concurrency, which is the minimum of the concurrency values across all eight internal collections. ```APIDOC ## Concurrency() ### Description Returns the configured concurrency, which is the minimum of the concurrency values across all eight internal collections. ### Method Concurrency() ### Returns - **uint16** - The configured concurrency. ### Signature ```go func (config *ConfigHash) Concurrency() uint16 ``` ``` -------------------------------- ### SizeManagerFromMemory function signature (not implemented) Source: https://github.com/51degrees/device-detection-go Signature for SizeManagerFromMemory, which is not implemented in this release. It always returns (0, nil) without performing any work, as marked by TODO comments in the source. ```go // TODO: To be implemeted func (config *ConfigHash) SizeManagerFromMemory( properties string, memory unsafe.Pointer, size uint64) (s uint64, err error) { // TODO: To be implemeted return 0, nil } ``` -------------------------------- ### Add method signature Source: https://github.com/51degrees/device-detection-go Adds a new evidence entry, matching the C API fiftyoneDegreesEvidenceAddString. Key and value are copied into C strings and freed when Free() is called. Always returns nil error. ```go func (evidence *Evidence) Add( prefix EvidencePrefix, key string, value string) error ```