### Complete NATS Server Startup Flow Source: https://github.com/nats-io/nats-server/blob/main/_autodocs/api-reference/startup-options.md A comprehensive example demonstrating the typical startup sequence for a NATS server programmatically. It includes parsing options, creating the server, configuring logging, starting the server, and waiting for shutdown. ```go package main import ( "flag" "os" "log" "github.com/nats-io/nats-server/v2/server" ) func main() { // Parse options fs := flag.NewFlagSet("nats-server", flag.ExitOnError) opts, err := server.ConfigureOptions(fs, os.Args[1:], func() { os.Exit(0) }, // version fs.Usage, // help server.PrintTLSHelpAndDie) if err != nil { server.PrintAndDie(err.Error()) } // Create server s, err := server.NewServer(opts) if err != nil { server.PrintAndDie(err.Error()) } // Configure logging s.ConfigureLogger() // Start server (non-blocking) s.Start() log.Printf("NATS server listening on %s", s.Addr()) // Wait for shutdown signal s.WaitForShutdown() } ``` -------------------------------- ### Example Subject Permission Configuration Source: https://github.com/nats-io/nats-server/blob/main/_autodocs/types.md An example demonstrating how to configure allowed and denied subjects using wildcards. This configuration restricts access to 'admin.>' subjects. ```go sub := &SubjectPermission{ Allow: []string{"orders.*", "updates.>"}, Deny: []string{"admin.>"}, } ``` -------------------------------- ### Start HTTP Monitoring Source: https://github.com/nats-io/nats-server/blob/main/_autodocs/api-reference/server.md Starts the HTTP monitoring server. Returns an error if monitoring cannot be started. ```go func (s *Server) StartMonitoring() error ``` -------------------------------- ### Start NATS Server with Options Source: https://github.com/nats-io/nats-server/blob/main/_autodocs/README.md Initializes and starts a NATS server programmatically using a provided Options struct. Includes basic logger configuration and graceful shutdown handling. ```go package main import ( "github.com/nats-io/nats-server/v2/server" ) func main() { opts := &server.Options{ Host: "0.0.0.0", Port: 4222, } s, err := server.NewServer(opts) if err != nil { panic(err) } s.ConfigureLogger() s.Start() defer s.Shutdown() s.WaitForShutdown() } ``` -------------------------------- ### Start HTTP Monitoring (No Return) Source: https://github.com/nats-io/nats-server/blob/main/_autodocs/api-reference/server.md Starts HTTP monitoring on the configured HTTP port. This method does not return any value. ```go func (s *Server) StartHTTPMonitoring() ``` -------------------------------- ### StartMonitoring Source: https://github.com/nats-io/nats-server/blob/main/_autodocs/api-reference/server.md Starts the HTTP monitoring server. Returns an error if the monitoring cannot be started. ```APIDOC ## StartMonitoring ### Description Starts the HTTP monitoring server. ### Returns - `error`: Error if monitoring cannot be started ``` -------------------------------- ### Create and Start NATS Server Programmatically Source: https://github.com/nats-io/nats-server/blob/main/_autodocs/quick-reference.md Instantiate and start a NATS server by providing options directly in the code. Remember to defer the shutdown process. ```go opts := &server.Options{ Host: "0.0.0.0", Port: 4222, } s, _ := server.NewServer(opts) s.Start() defers.Shutdown() ``` -------------------------------- ### GET /subsz Response Example Source: https://github.com/nats-io/nats-server/blob/main/_autodocs/endpoints.md Example JSON response from the /subsz endpoint, showing subscription counts and details for specific subjects. ```json { "num_subscriptions": 50, "num_cache": 25, "limit": 1024, "offset": 0, "subscriptions": [ { "subject": "orders.வுகளை", "num_qsubs": 2, "num_subs": 3 }, { "subject": "events.created", "num_qsubs": 0, "num_subs": 2 } ] } ``` -------------------------------- ### Create and Start NATS Server Source: https://github.com/nats-io/nats-server/blob/main/_autodocs/README.md Creates a new NATS server instance with specified options and starts its operation. The server will run until shutdown is initiated. ```go package server // Create server with options opts := &Options{Port: 4222} s, err := NewServer(opts) if err != nil { log.Fatal(err) } // Start server s.Start() // Block until shutdown s.WaitForShutdown() ``` -------------------------------- ### GET /leafz Response Example Source: https://github.com/nats-io/nats-server/blob/main/_autodocs/endpoints.md Example JSON response from the /leafz endpoint, showing details of connected leaf nodes. ```json { "num_leafnodes": 1, "leafnodes": [ { "account": "myapp", "ip": "192.168.1.100", "port": 54321, "subscriptions": 10, "in_msgs": 10000, "out_msgs": 10000, "in_bytes": 500000, "out_bytes": 500000, "uptime": "1h30m", "idle": "5s", "last_activity": "2024-01-15T15:30:40Z" } ] } ``` -------------------------------- ### Start HTTPS Monitoring Source: https://github.com/nats-io/nats-server/blob/main/_autodocs/api-reference/server.md Starts HTTPS monitoring on the configured HTTPS port. This method does not return any value. ```go func (s *Server) StartHTTPSMonitoring() ``` -------------------------------- ### GET /leafz Request Example Source: https://github.com/nats-io/nats-server/blob/main/_autodocs/endpoints.md Example of a request to the /leafz endpoint to retrieve information about leaf node connections. ```http GET /leafz HTTP/1.1 Host: localhost:8222 ``` -------------------------------- ### GET /subsz Request Example Source: https://github.com/nats-io/nats-server/blob/main/_autodocs/endpoints.md Example of a request to the /subsz endpoint to retrieve subscription statistics, optionally filtered by account. ```http GET /subsz?account=myaccount HTTP/1.1 Host: localhost:8222 ``` -------------------------------- ### Request GET /connz with Query Parameters Source: https://github.com/nats-io/nats-server/blob/main/_autodocs/endpoints.md Example HTTP request to retrieve details about active client connections, with options to limit results, sort by uptime, and include subscription information. Use query parameters to filter and sort connection data. ```http GET /connz?limit=100&sort=uptime HTTP/1.1 Host: localhost:8222 ``` -------------------------------- ### Start Monitoring Server Source: https://github.com/nats-io/nats-server/blob/main/_autodocs/api-reference/monitoring.md Initiates the NATS monitoring server. Check the returned error for any issues during startup. ```go s, _ := server.NewServer(opts) if err := s.StartMonitoring(); err != nil { log.Fatal(err) } ``` -------------------------------- ### GET /routez Response Example Source: https://github.com/nats-io/nats-server/blob/main/_autodocs/endpoints.md Example JSON response from the /routez endpoint, detailing active cluster routes and their statistics. ```json { "server_id": "NABCZM3YXQXJXQJD6Y4XAHDX5VBCCBVGSWH2WTPFDFQPHIABVAHGPKNE", "now": "2024-01-15T15:30:45Z", "import": null, "export": null, "num_routes": 1, "routes": [ { "rid": 1, "remote_id": "NCSMU6LKFXS5UQGJMFRVJ4GHQUOSJMPRGQ...6P3RNU", "remote_name": "nats-server-2", "url": "nats://127.0.0.1:6222", "pending": 0, "in_msgs": 50000, "out_msgs": 50000, "in_bytes": 2500000, "out_bytes": 2500000, "subscriptions": 50, "subscriptions_list": null, "last_activity": "2024-01-15T15:30:44Z" } ] } ``` -------------------------------- ### Enable Monitoring with Options Source: https://github.com/nats-io/nats-server/blob/main/_autodocs/api-reference/monitoring.md Configure and start the HTTP monitoring server using the Options struct. Ensure the HTTPPort is set to the desired value. ```go opts := &Options{ HTTPHost: "localhost", // Listen address HTTPPort: 8222, // Listen port HTTPBasePath: "/", // Base URL path } s, _ := server.NewServer(opts) s.StartMonitoring() ``` -------------------------------- ### GET /routez Request Example Source: https://github.com/nats-io/nats-server/blob/main/_autodocs/endpoints.md Example of a request to the /routez endpoint to retrieve information about cluster route connections. ```http GET /routez HTTP/1.1 Host: localhost:8222 ``` -------------------------------- ### StartHTTPMonitoring Source: https://github.com/nats-io/nats-server/blob/main/_autodocs/api-reference/server.md Starts HTTP monitoring on the configured HTTP port. ```APIDOC ## StartHTTPMonitoring ### Description Starts HTTP monitoring on the configured HTTP port. ``` -------------------------------- ### Start Source: https://github.com/nats-io/nats-server/blob/main/_autodocs/api-reference/server.md Starts the NATS server, enabling it to accept client connections and begin processing messages. This is a non-blocking call. ```APIDOC ## Start ### Description Starts the server, accepting client connections and beginning processing. ### Method `Start` ### Behavior - Binds to configured listening ports - Starts accepting client, route, gateway, and leaf node connections - Initializes monitoring HTTP server if configured - Non-blocking call that begins server operation ### Example ```go s, _ := server.NewServer(opts) s.Start() // Server is now running ``` ``` -------------------------------- ### Start NATS Server Source: https://github.com/nats-io/nats-server/blob/main/_autodocs/api-reference/startup-options.md Starts the NATS server, enabling it to accept client connections. This is a non-blocking call that initiates binding to the client listen address and begins accepting connections. ```go s, _ := server.NewServer(opts) s.Start() log.Println("Server started") // Server runs in background ``` -------------------------------- ### Create and Start NATS Server from Config Source: https://github.com/nats-io/nats-server/blob/main/_autodocs/quick-reference.md Create a NATS server instance by processing a configuration file. Ensure to defer the shutdown and wait for it to complete. ```go opts, _ := server.ProcessConfigFile("nats.conf") s, _ := server.NewServer(opts) s.ConfigureLogger() s.Start() defers.Shutdown() s.WaitForShutdown() ``` -------------------------------- ### GET /jsz Request Example Source: https://github.com/nats-io/nats-server/blob/main/_autodocs/endpoints.md Example of a request to the /jsz endpoint to retrieve JetStream status, optionally filtered by account, stream, or consumer. ```http GET /jsz?account=myapp HTTP/1.1 Host: localhost:8222 ``` -------------------------------- ### Enable Go Profiling Source: https://github.com/nats-io/nats-server/blob/main/_autodocs/api-reference/monitoring.md Enable Go profiling by setting the ProfPort option when starting the NATS server. ```go opts := &Options{ ProfPort: 6060, } s.StartProfiler() ``` -------------------------------- ### StartHTTPSMonitoring Source: https://github.com/nats-io/nats-server/blob/main/_autodocs/api-reference/server.md Starts HTTPS monitoring on the configured HTTPS port. ```APIDOC ## StartHTTPSMonitoring ### Description Starts HTTPS monitoring on the configured HTTPS port. ``` -------------------------------- ### Response Body for GET /varz Source: https://github.com/nats-io/nats-server/blob/main/_autodocs/endpoints.md Example JSON response body for the /varz endpoint, detailing server variables, statistics, and operational metrics. Includes fields like server ID, version, uptime, and message counts. ```json { "server_id": "NABCZM3YXQXJXQJD6Y4XAHDX5VBCCBVGSWH2WTPFDFQPHIABVAHGPKNE", "server_name": "nats-server", "version": "2.10.0", "proto": 1, "git_commit": "abc1234", "go": "go1.21.5", "host": "0.0.0.0", "port": 4222, "headers": true, "max_connections": 65536, "max_subscriptions": 0, "max_control_line": 4096, "max_payload": 1048576, "client_connect_urls": [ "nats://127.0.0.1:4222" ], "ws_connect_urls": [], "ping_interval": 120000000000, "ping_max": 2, "http_host": "0.0.0.0", "http_port": 8222, "https_port": 0, "auth_timeout": 1, "tls_timeout": 5, "tls": false, "tls_verify": false, "tls_required": false, "uptime": "5h30m12s", "now": "2024-01-15T15:30:45Z", "connections": 2, "total_connections": 10, "active_accounts": 1, "subscriptions": 25, "default_vhosts": [], "total_msgs_in": 1000000, "total_msgs_out": 1000000, "total_bytes_in": 50000000, "total_bytes_out": 50000000, "slow_consumers": 0, "routes": 0, "gateways": 0, "leaf_nodes": 0, "in_msgs": 1000000, "out_msgs": 1000000, "in_bytes": 50000000, "out_bytes": 50000000 } ``` -------------------------------- ### Request GET /varz Source: https://github.com/nats-io/nats-server/blob/main/_autodocs/endpoints.md Example HTTP request to retrieve comprehensive server statistics and configuration. This endpoint returns all server variables by default. ```http GET /varz HTTP/1.1 Host: localhost:8222 ``` -------------------------------- ### Example NATS Server Configuration File Source: https://github.com/nats-io/nats-server/blob/main/_autodocs/configuration.md A sample configuration file demonstrating various NATS server settings. It includes options for server name, host, port, HTTP monitoring, logging, authentication, TLS, clustering, and JetStream. ```conf # Server settings server_name: "nats-1" host: "0.0.0.0" port: 4222 # HTTP monitoring http_port: 8222 # Logging debug: false trace: false logtime: true log_file: "/var/log/nats.log" # Authentication authorization { users [ { user: "alice", pass: "foobar" } { user: "bob", pass: "barbaz" } ] } # TLS tls { cert_file: "/etc/nats/certs/server.pem" key_file: "/etc/nats/certs/server-key.pem" verify: false } # Clustering cluster { host: "0.0.0.0" port: 6222 routes [ "nats://other-server:6222" ] } # JetStream jetstream { store_dir: "/var/lib/nats/jetstream" max_memory: 1GB max_file_store: 10GB } ``` -------------------------------- ### Get Account Name Source: https://github.com/nats-io/nats-server/blob/main/_autodocs/api-reference/accounts.md Retrieves the name of the account. ```go func (a *Account) GetName() string ``` -------------------------------- ### Get Server String Representation Source: https://github.com/nats-io/nats-server/blob/main/_autodocs/api-reference/server.md Returns a string representation that uniquely identifies the server. ```go func (s *Server) String() string ``` -------------------------------- ### Typical NATS Server Deployment Source: https://github.com/nats-io/nats-server/blob/main/_autodocs/quick-reference.md A standard Go program structure for deploying a NATS server. It includes loading configuration, creating, configuring logger, starting, and waiting for shutdown. ```go func main() { // 1. Load configuration opts, err := server.ProcessConfigFile("nats.conf") if err != nil { server.PrintAndDie(err.Error()) } // 2. Create server s, err := server.NewServer(opts) if err != nil { server.PrintAndDie(err.Error()) } // 3. Configure logging s.ConfigureLogger() // 4. Start server s.Start() log.Printf("NATS server ready on %v", s.Addr()) // 5. Wait for shutdown s.WaitForShutdown() } ``` -------------------------------- ### Get Server Information Source: https://github.com/nats-io/nats-server/blob/main/_autodocs/quick-reference.md Retrieve and print basic server information such as its ID, name, and network address. This is helpful for verifying server status. ```go // Get server info fmt.Println(s.ID(), s.Name(), s.Addr()) ``` -------------------------------- ### Enable Go Profiling Programmatically Source: https://github.com/nats-io/nats-server/blob/main/_autodocs/endpoints.md Go code snippet to enable Go profiling by setting the ProfPort option and starting the profiler. ```go opts.ProfPort = 6060 s.StartProfiler() ``` -------------------------------- ### Get Configuration Load Time Source: https://github.com/nats-io/nats-server/blob/main/_autodocs/api-reference/server.md Retrieves the time when the server's configuration was last loaded. ```go func (s *Server) ConfigTime() time.Time ``` -------------------------------- ### Get Server Name Source: https://github.com/nats-io/nats-server/blob/main/_autodocs/api-reference/server.md Returns the configured name of the NATS server. ```go func (s *Server) Name() string ``` -------------------------------- ### Response Body for GET /connz Source: https://github.com/nats-io/nats-server/blob/main/_autodocs/endpoints.md Example JSON response body for the /connz endpoint, showing active client connection details. Includes fields like CID, start time, uptime, message counts, and client name. ```json { "num_connections": 2, "total": 2, "offset": 0, "limit": 1024, "connections": [ { "cid": 1, "kind": "client", "type": "nats", "ip": "127.0.0.1", "port": 54321, "start": "2024-01-15T10:00:00Z", "last_activity": "2024-01-15T15:30:45Z", "uptime": "5h30m45s", "idle": "2s", "pending_bytes": 0, "in_msgs": 100000, "out_msgs": 100000, "in_bytes": 5000000, "out_bytes": 5000000, "subscriptions": 5, "name": "client-app-1", "lang": "go", "version": "1.19.0", "account": "app-1", "rtt": "2ms", "rtt_nanoseconds": 2000000 } ] } ``` -------------------------------- ### Load Server Configuration and Create Server Source: https://github.com/nats-io/nats-server/blob/main/_autodocs/README.md Loads server configuration from a file and then creates a new server instance with those options. Error handling for both steps is included. ```go opts, err := server.ProcessConfigFile("nats.conf") if err != nil { log.Fatal(err) } s, err := server.NewServer(opts) if err != nil { log.Fatal(err) } ``` -------------------------------- ### Get Client Connection URL Source: https://github.com/nats-io/nats-server/blob/main/_autodocs/api-reference/server.md Retrieves the client connection URL for the server, formatted as nats://host:port. ```go func (s *Server) ClientURL() string ``` -------------------------------- ### GET /debug/pprof/* - Go Profiling Source: https://github.com/nats-io/nats-server/blob/main/_autodocs/endpoints.md Provides access to standard Go profiling endpoints, allowing for in-depth performance analysis. Profiling must be explicitly enabled in the server configuration. ```APIDOC ## GET /debug/pprof/* - Go Profiling ### Description Standard Go profiling endpoints (requires profiling to be enabled). ### Enable Profiling ```conf prof_port: 6060 ``` Or programmatically: ```go opts.ProfPort = 6060 s.StartProfiler() ``` ### Available Profiles | Endpoint | Description | |----------|-------------| | `/debug/pprof/` | Profile index and list | | `/debug/pprof/heap` | Memory allocations | | `/debug/pprof/goroutine` | Goroutines | | `/debug/pprof/threadcreate` | Thread creation | | `/debug/pprof/block` | Block contention | | `/debug/pprof/mutex` | Mutex contention | ### Usage Examples ```bash # Get heap profile go tool pprof http://localhost:6060/debug/pprof/heap # Get goroutine dump curl http://localhost:6060/debug/pprof/goroutine # Get CPU profile (30 seconds) go tool pprof http://localhost:6060/debug/pprof/profile?seconds=30 ``` ``` -------------------------------- ### Register and Manage Account Limits Source: https://github.com/nats-io/nats-server/blob/main/_autodocs/README.md Demonstrates how to register a new account or look up an existing one, and then check its connection limits and current usage. ```go acc, _ := s.RegisterAccount("myapp") acc.MaxActiveConnections() // Get limit acc.NumConnections() // Get current usage ``` -------------------------------- ### Get Connection Information Source: https://github.com/nats-io/nats-server/blob/main/_autodocs/api-reference/monitoring.md Retrieves details about all client connections, with options to filter and sort the results. Use this to monitor active clients and their statistics. ```bash curl "http://localhost:8222/connz?limit=5&sort=uptime" ``` -------------------------------- ### NATS Monitoring Setup and Endpoints Source: https://github.com/nats-io/nats-server/blob/main/_autodocs/quick-reference.md Enable HTTP monitoring for the NATS server by setting the HTTP port and host in the options. This allows access to various monitoring endpoints for server stats, connections, subscriptions, and more. ```go // Enable HTTP monitoring opts.HTTPPort = 8222 opts.HTTPHost = "0.0.0.0" // Start monitoring s.StartMonitoring() // Get address addr := s.MonitorAddr() // Get handler (for custom HTTP server) handler := s.HTTPHandler() // Endpoints (curl examples) // GET /varz - Server stats // GET /connz - Connections // GET /subsz - Subscriptions // GET /routez - Routes // GET /jsz - JetStream // GET /healthz - Health check ``` -------------------------------- ### Get CPU Profile using Go Tool Source: https://github.com/nats-io/nats-server/blob/main/_autodocs/endpoints.md Command to retrieve a CPU profile for a specified duration (30 seconds) from the NATS server's profiling endpoint using 'go tool pprof'. ```bash go tool pprof http://localhost:6060/debug/pprof/profile?seconds=30 ``` -------------------------------- ### NATS Server HTTP Configuration Source: https://github.com/nats-io/nats-server/blob/main/_autodocs/endpoints.md Example configuration for enabling and setting up HTTP monitoring endpoints on the NATS server. Ensure http_host and http_port are correctly configured. ```conf http_host: 0.0.0.0 http_port: 8222 http_base_path: / ``` -------------------------------- ### Get Heap Profile using Go Tool Source: https://github.com/nats-io/nats-server/blob/main/_autodocs/endpoints.md Command to retrieve the heap profile from the NATS server's profiling endpoint using the 'go tool pprof' command. ```bash go tool pprof http://localhost:6060/debug/pprof/heap ``` -------------------------------- ### NATS Configuration from File Source: https://github.com/nats-io/nats-server/blob/main/_autodocs/quick-reference.md Load NATS server configuration from a file, clone the options, and then create a new server instance with the processed configuration. ```go // Parse config file opts, err := server.ProcessConfigFile("nats.conf") if err != nil { log.Fatal(err) } // Clone options opts2 := opts.Clone() // Apply and create server s, _ := server.NewServer(opts) ``` -------------------------------- ### NATS Server Lifecycle Management Source: https://github.com/nats-io/nats-server/blob/main/_autodocs/quick-reference.md Manage the lifecycle of a NATS server, including creation, checking its running status, starting, waiting for readiness, graceful shutdown, and retrieving server information. ```go // Create s, err := server.NewServer(opts) // Check if running if s.Running() { } // Start s.Start() // Wait for ready s.ReadyForConnections(10 * time.Second) // Graceful shutdown s.Shutdown() // Block until shutdown complete s.WaitForShutdown() // Get info s.Name() // Server name s.ID() // Unique ID s.Addr() // Listen address s.ClientURL() // nats://host:port ``` -------------------------------- ### Get Local Client Connections Source: https://github.com/nats-io/nats-server/blob/main/_autodocs/api-reference/accounts.md Returns the number of client connections established directly on the current server for this account. It excludes system accounts and leaf nodes. ```go func (a *Account) NumLocalConnections() int ``` -------------------------------- ### Load Server Configuration from File Source: https://github.com/nats-io/nats-server/blob/main/_autodocs/quick-reference.md Process a configuration file to load server options. This is useful for managing complex configurations externally. Ensure the file path is correct. ```go // Check configuration opts, err := server.ProcessConfigFile("nats.conf") ``` -------------------------------- ### Create New Account Source: https://github.com/nats-io/nats-server/blob/main/_autodocs/api-reference/accounts.md Creates a new account instance with a given name. The created account must then be registered with a server instance. ```go acc := server.NewAccount("app-1") server := &server.Server{} server.RegisterAccount(acc) ``` -------------------------------- ### Define Accounts in Server Options Source: https://github.com/nats-io/nats-server/blob/main/_autodocs/api-reference/accounts.md Use the `server.NewAccount` function to create account objects and then include them in the `Accounts` field of the `server.Options` struct. ```go acc1 := server.NewAccount("alice") acc2 := server.NewAccount("bob") opts := &server.Options{ Accounts: []*server.Account{acc1, acc2}, } ``` -------------------------------- ### Get Subscription Information Source: https://github.com/nats-io/nats-server/blob/main/_autodocs/api-reference/monitoring.md Retrieves subscription statistics. This endpoint can be filtered by account to get specific subscription counts. ```bash curl http://localhost:8222/subsz ``` -------------------------------- ### New Source: https://github.com/nats-io/nats-server/blob/main/_autodocs/api-reference/server.md Legacy constructor that creates a new NATS server instance without explicit error handling. Use `NewServer` for robust initialization. ```APIDOC ## New ### Description Legacy constructor that creates a new server without error handling. ### Method `New` ### Parameters #### Path Parameters - **opts** (`*Options`) - Required - Server configuration options ### Returns - `*Server`: Initialized server instance ``` -------------------------------- ### Server Options with WebSocket Source: https://github.com/nats-io/nats-server/blob/main/_autodocs/quick-reference.md Configure server options including the client port and WebSocket settings. Set NoTLS to true for testing purposes. ```go opts := &server.Options{ Port: 4222, Websocket: server.WebsocketOpts{ Host: "0.0.0.0", Port: 8080, NoTLS: true, // For testing }, } ``` -------------------------------- ### Set System Account by Name Source: https://github.com/nats-io/nats-server/blob/main/_autodocs/api-reference/server.md Sets the system account for the server by providing its name. An error is returned if the specified account does not exist. ```go func (s *Server) SetSystemAccount(accName string) error ``` -------------------------------- ### Process Configuration File Source: https://github.com/nats-io/nats-server/blob/main/_autodocs/configuration.md Parses a configuration file to load NATS server options. Use this when initializing a server from a configuration file. ```go func ProcessConfigFile(configFile string) (*Options, error) ``` ```go opts, err := server.ProcessConfigFile("nats.conf") if err != nil { log.Fatal(err) } s, _ := server.NewServer(opts) ``` -------------------------------- ### ConfigureOptions Source: https://github.com/nats-io/nats-server/blob/main/_autodocs/api-reference/startup-options.md Parses command-line arguments and configuration files into Options. It takes a flag set, arguments, and callbacks for version and help messages. ```APIDOC ## ConfigureOptions ### Description Parses command-line arguments and configuration files into Options. It takes a flag set, arguments, and callbacks for version and help messages. ### Function Signature ```go func ConfigureOptions(fs *flag.FlagSet, args []string, printVersion, printHelp, printTLSHelp func()) (*Options, error) ``` ### Parameters #### Function Parameters - **fs** (*flag.FlagSet) - Flag set for parsing - **args** ([]string) - Command-line arguments - **printVersion** (func()) - Callback for `-v` flag - **printHelp** (func()) - Callback for `-h` flag - **printTLSHelp** (func()) - Callback for `--help_tls` flag ### Returns - **(*Options)** - Parsed and validated options - **error** - Configuration error if invalid ### Command-Line Flags | Flag | Short | Type | Description | |------|-------|------|-------------| | `--addr` | `-a` | string | Bind address (default: 0.0.0.0) | | `--port` | `-p` | int | Port (default: 4222) | | `--config` | `-c` | string | Config file path | | `--name` | `-n` | string | Server name | | `--http_port` | `-m` | int | HTTP monitoring port | | `--https_port` | `-ms` | int | HTTPS monitoring port | | `--debug` | `-D` | — | Debug logging | | `--trace` | `-V` | — | Protocol tracing | | `--logfile` | `-l` | string | Log file path | | `--pid` | `-P` | string | PID file path | | `--jetstream` | `-js` | — | Enable JetStream | | `--store_dir` | `-sd` | string | JetStream storage dir | ``` -------------------------------- ### Get Cluster Name Source: https://github.com/nats-io/nats-server/blob/main/_autodocs/api-reference/server.md Retrieves the name of the cluster the server belongs to. ```go func (s *Server) ClusterName() string ``` -------------------------------- ### Load Server Configuration from File Source: https://github.com/nats-io/nats-server/blob/main/_autodocs/README.md Loads NATS server configuration options from a specified configuration file. This is one of the primary ways to configure the server. ```go opts, _ := server.ProcessConfigFile("nats.conf") s, _ := server.NewServer(opts) ``` -------------------------------- ### Get Number of Stalled Clients Source: https://github.com/nats-io/nats-server/blob/main/_autodocs/api-reference/server.md Retrieves the count of client connections that are currently stalled. ```go func (s *Server) NumStalledClients() int64 ``` -------------------------------- ### Get Cluster Connection Address Source: https://github.com/nats-io/nats-server/blob/main/_autodocs/api-reference/server.md Retrieves the network address used for cluster connections. ```go func (s *Server) ClusterAddr() *net.TCPAddr ``` -------------------------------- ### Configure Server Options with Flags and Args Source: https://github.com/nats-io/nats-server/blob/main/_autodocs/configuration.md Configures NATS server options by parsing command-line arguments and configuration files. This is typically used during server startup. ```go func ConfigureOptions(fs *flag.FlagSet, args []string, printVersion, printHelp, printTLSHelp func()) (*Options, error) ``` -------------------------------- ### Get HTTP Handler for Monitoring Source: https://github.com/nats-io/nats-server/blob/main/_autodocs/api-reference/server.md Retrieves the HTTP handler responsible for monitoring endpoints. ```go func (s *Server) HTTPHandler() http.Handler ``` -------------------------------- ### Lookup or Register Account and Check Limits Source: https://github.com/nats-io/nats-server/blob/main/_autodocs/README.md Retrieves an account by name, registering it if it doesn't exist, and then checks if the account has reached its maximum connection limit or reports current connection and subscription counts. ```go // Create account acc, isNew := s.LookupOrRegisterAccount("app-1") // Check limits if acc.MaxTotalConnectionsReached() { log.Println("Account full") } // Get statistics conns := acc.NumConnections() subs := acc.TotalSubs() ``` -------------------------------- ### Enable Go Profiling via Config Source: https://github.com/nats-io/nats-server/blob/main/_autodocs/api-reference/monitoring.md Alternatively, enable Go profiling by configuring the prof_port in the NATS server configuration file. ```conf prof_port: 6060 ``` -------------------------------- ### Get Server ID Source: https://github.com/nats-io/nats-server/blob/main/_autodocs/api-reference/server.md Returns the unique identifier string for the NATS server instance. ```go func (s *Server) ID() string ``` -------------------------------- ### Get Routed Subscriptions Source: https://github.com/nats-io/nats-server/blob/main/_autodocs/api-reference/accounts.md Returns the count of subscriptions that are configured to be routed to other NATS servers. ```go func (a *Account) RoutedSubs() int ``` -------------------------------- ### Get Total Subscriptions Source: https://github.com/nats-io/nats-server/blob/main/_autodocs/api-reference/accounts.md Returns the total number of active subscriptions within this account. ```go func (a *Account) TotalSubs() int ``` -------------------------------- ### NewServer Source: https://github.com/nats-io/nats-server/blob/main/_autodocs/api-reference/startup-options.md Creates a new NATS server instance with the provided configuration options. It returns the server instance or an error if the options are invalid. ```APIDOC ## NewServer ### Description Creates a new NATS server instance with the provided configuration options. It returns the server instance or an error if the options are invalid. ### Function Signature ```go func NewServer(opts *Options) (*Server, error) ``` ### Parameters #### Function Parameters - **opts** (*Options) - Configuration options ### Returns - **(*Server)** - Initialized server instance - **error** - Error if options invalid ### Errors - Invalid port number - TLS configuration error - Account configuration error - JetStream setup error ``` -------------------------------- ### Get Number of Slow Consumers Source: https://github.com/nats-io/nats-server/blob/main/_autodocs/api-reference/server.md Retrieves the count of client connections identified as slow consumers. ```go func (s *Server) NumSlowConsumers() int64 ``` -------------------------------- ### Get Global Account Source: https://github.com/nats-io/nats-server/blob/main/_autodocs/api-reference/server.md Retrieves the global or default account instance used by the NATS server. ```go func (s *Server) GlobalAccount() *Account ``` -------------------------------- ### NewServerFromConfig Source: https://github.com/nats-io/nats-server/blob/main/_autodocs/api-reference/startup-options.md Creates a new NATS server instance directly from a configuration file. It takes pre-parsed options as input. ```APIDOC ## NewServerFromConfig ### Description Creates a new NATS server instance directly from a configuration file. It takes pre-parsed options as input. ### Function Signature ```go func NewServerFromConfig(opts *Options) (*Server, error) ``` ### Parameters #### Function Parameters - **opts** (*Options) - Pre-parsed options ### Returns - **(*Server)** - Server instance - **error** - Configuration error ``` -------------------------------- ### Configure Server Logger Source: https://github.com/nats-io/nats-server/blob/main/_autodocs/api-reference/startup-options.md Configures the server's logging behavior based on the provided options. This method must be called after `NewServer` and sets up file logging, syslog, log levels, and timestamps. ```go s, _ := server.NewServer(opts) s.ConfigureLogger() // Configure based on opts s.Start() ``` -------------------------------- ### Enable Debug and Trace Logging Source: https://github.com/nats-io/nats-server/blob/main/_autodocs/quick-reference.md Enable debug logging to see detailed server activity and protocol tracing for in-depth analysis. These options are set on the server options struct. ```go // Enable debug logging opts.Debug = true // Enable protocol tracing opts.Trace = true ``` -------------------------------- ### Get Active Cluster Peers Source: https://github.com/nats-io/nats-server/blob/main/_autodocs/api-reference/server.md Retrieves a list of active peer server IDs within the cluster. ```go func (s *Server) ActivePeers() (peers []string) ``` -------------------------------- ### Programmatically Process Configuration File Source: https://github.com/nats-io/nats-server/blob/main/_autodocs/api-reference/startup-options.md Demonstrates how to programmatically parse a NATS server configuration file using the `ProcessConfigFile` function. This allows for configuration validation and loading within an application. ```go opts, err := server.ProcessConfigFile("nats.conf") if err != nil { log.Fatal(err) } // File was successfully parsed ``` -------------------------------- ### Get System Account Source: https://github.com/nats-io/nats-server/blob/main/_autodocs/api-reference/server.md Retrieves the system account instance, which is utilized for internal NATS server operations. ```go func (s *Server) SystemAccount() *Account ``` -------------------------------- ### Get Total Loaded Account Count Source: https://github.com/nats-io/nats-server/blob/main/_autodocs/api-reference/server.md Returns the total count of all accounts that have been loaded into the NATS server. ```go func (s *Server) NumLoadedAccounts() int ``` -------------------------------- ### Export Client Certificate and Key to PKCS12 Source: https://github.com/nats-io/nats-server/blob/main/test/configs/certs/tlsauth/certstore/pkcs12.md Use this command to create a PKCS12 bundle containing a client's certificate and private key. This is useful for applications that require a single file for client authentication. ```bash openssl pkcs12 -export -inkey ./client-key.pem -in ./client.pem -out client.p12 ``` -------------------------------- ### Handle Server Creation Errors Source: https://github.com/nats-io/nats-server/blob/main/_autodocs/README.md Check for errors during NATS server initialization. This pattern is crucial for validating server options. ```go s, err := server.NewServer(opts) if err != nil { // Configuration error, check opts log.Fatal(err) } ``` -------------------------------- ### Get Active Account Count Source: https://github.com/nats-io/nats-server/blob/main/_autodocs/api-reference/server.md Returns the number of accounts that currently have active client connections to the server. ```go func (s *Server) NumActiveAccounts() int32 ``` -------------------------------- ### ProcessConfigFile Source: https://github.com/nats-io/nats-server/blob/main/_autodocs/api-reference/startup-options.md Parses a configuration file into Options. It takes the path to the configuration file as input. ```APIDOC ## ProcessConfigFile ### Description Parses a configuration file into Options. It takes the path to the configuration file as input. ### Function Signature ```go func ProcessConfigFile(configFile string) (*Options, error) ``` ### Parameters #### Function Parameters - **configFile** (string) - Path to configuration file ### Returns - **(*Options)** - Parsed options - **error** - Parse error if invalid ``` -------------------------------- ### Get Number of Connected Clients Source: https://github.com/nats-io/nats-server/blob/main/_autodocs/api-reference/server.md Returns the current count of active client connections to the NATS server. ```go func (s *Server) NumClients() int ``` -------------------------------- ### Get Server Listening Address Source: https://github.com/nats-io/nats-server/blob/main/_autodocs/api-reference/server.md Returns the network address (net.Addr) at which the NATS server is listening for client connections. ```go func (s *Server) Addr() net.Addr ``` -------------------------------- ### Get Number of Active Routes Source: https://github.com/nats-io/nats-server/blob/main/_autodocs/api-reference/server.md Returns the current count of active route connections established with the NATS server. ```go func (s *Server) NumRoutes() int ``` -------------------------------- ### Check Server Readiness for Connections Source: https://github.com/nats-io/nats-server/blob/main/_autodocs/api-reference/server.md Blocks until the server is ready to accept connections or a specified timeout duration is reached. Returns true if ready, false if timeout occurs. ```go func (s *Server) ReadyForConnections(dur time.Duration) bool ``` -------------------------------- ### Get Remote Leaf Node Connections Source: https://github.com/nats-io/nats-server/blob/main/_autodocs/api-reference/accounts.md Returns the number of leaf node connections that are established through remote NATS servers. ```go func (a *Account) NumRemoteLeafNodes() int ``` -------------------------------- ### Get Cluster Route Information Source: https://github.com/nats-io/nats-server/blob/main/_autodocs/api-reference/monitoring.md Retrieves information about cluster routes. This is useful for understanding the state of NATS server clusters. ```bash curl http://localhost:8222/routez ``` -------------------------------- ### 404 Not Found Error Response Source: https://github.com/nats-io/nats-server/blob/main/_autodocs/endpoints.md Example JSON response for a 404 Not Found error, typically returned when a requested resource does not exist. ```json { "error": "connection not found" } ``` -------------------------------- ### Basic NATS Server Configuration Source: https://github.com/nats-io/nats-server/blob/main/_autodocs/quick-reference.md Configure essential NATS server options including server name, host, port, connection limits, payload size, authentication, TLS, monitoring, and JetStream. ```go opts := &server.Options{ ServerName: "nats-1", Host: "0.0.0.0", Port: 4222, Debug: false, Trace: false, MaxConn: 65536, MaxPayload: 1048576, // 1MB // Authentication Username: "alice", Password: "secret", // TLS TLS: true, TLSCert: "/etc/nats/certs/server.crt", TLSKey: "/etc/nats/certs/server.key", // Monitoring HTTPPort: 8222, // JetStream JetStream: true, StoreDir: "/data/jetstream", } s, _ := server.NewServer(opts) ``` -------------------------------- ### Create New NATS Server Instance Source: https://github.com/nats-io/nats-server/blob/main/_autodocs/api-reference/startup-options.md Creates a new NATS server instance with the provided configuration options. Ensure options are validated before passing them to this function. ```go func NewServer(opts *Options) (*Server, error) ``` ```go opts := &Options{ Host: "0.0.0.0", Port: 4222, } s, err := server.NewServer(opts) if err != nil { panic(err) } ``` -------------------------------- ### Get Server Node Name Source: https://github.com/nats-io/nats-server/blob/main/_autodocs/api-reference/server.md Returns the node name of the NATS server, which may differ from its general name in clustered environments. ```go func (s *Server) NodeName() string ``` -------------------------------- ### MQTT Options Structure Source: https://github.com/nats-io/nats-server/blob/main/_autodocs/types.md Configuration for MQTT protocol support. This allows NATS to act as an MQTT broker, with options for replication, storage, and timeouts. ```go type MQTTOpts struct { Host string Port int NoAuthUser string Username string Password string Token string JsDomain string StreamReplicas int ConsumerReplicas int ConsumerMemoryStorage bool ConsumerInactiveThreshold time.Duration AuthTimeout float64 TLSConfig *tls.Config TLSMap bool TLSTimeout float64 TLSPinnedCerts PinnedCertSet AckWait time.Duration JSAPITimeout time.Duration MaxAckPending uint16 } ``` -------------------------------- ### Define User with Username/Password Source: https://github.com/nats-io/nats-server/blob/main/_autodocs/types.md Represents a user for basic username and password authentication. It can include specific publish/subscribe permissions. ```go type User struct { Username string Password string Permissions *Permissions } ``` -------------------------------- ### Get Number of Active Leaf Nodes Source: https://github.com/nats-io/nats-server/blob/main/_autodocs/api-reference/server.md Returns the current count of active leaf node connections managed by the NATS server. ```go func (s *Server) NumLeafNodes() int ``` -------------------------------- ### Get Maximum Active Connections Source: https://github.com/nats-io/nats-server/blob/main/_autodocs/api-reference/accounts.md Returns the maximum number of concurrent connections allowed for this account. A value of -1 indicates no limit. ```go func (a *Account) MaxActiveConnections() int ``` -------------------------------- ### Define Subject Permissions with Allow/Deny Lists Source: https://github.com/nats-io/nats-server/blob/main/_autodocs/types.md Specifies allowed and denied subject patterns for a user or connection. Denied subjects take precedence over allowed ones. ```go type SubjectPermission struct { Allow []string Deny []string } ``` -------------------------------- ### Create NATS Server from Configuration Source: https://github.com/nats-io/nats-server/blob/main/_autodocs/api-reference/startup-options.md Creates a NATS server instance directly from a configuration file. This is a convenience function that combines file processing and server creation. ```go func NewServerFromConfig(opts *Options) (*Server, error) ``` -------------------------------- ### Get Leaf Node Information Source: https://github.com/nats-io/nats-server/blob/main/_autodocs/api-reference/monitoring.md Retrieves information about connected leaf nodes. Use this to monitor leaf node connections and their activity. ```bash curl http://localhost:8222/leafz ``` -------------------------------- ### Get Monitoring HTTP Handler Source: https://github.com/nats-io/nats-server/blob/main/_autodocs/api-reference/monitoring.md Obtain the HTTP handler for the monitoring endpoints. This allows integration with custom HTTP servers or routing. ```go handler := s.HTTPHandler() // Can be used with custom HTTP server http.Handle("/nats", handler) ``` -------------------------------- ### Get Monitoring Server Address Source: https://github.com/nats-io/nats-server/blob/main/_autodocs/api-reference/monitoring.md Retrieve the network address of the running monitoring server. This can be useful for dynamically configuring clients or other services. ```go addr := s.MonitorAddr() if addr != nil { fmt.Printf("Monitor on %s:%d\n", addr.IP, addr.Port) } ``` -------------------------------- ### Lookup or Register Account Source: https://github.com/nats-io/nats-server/blob/main/_autodocs/api-reference/server.md Looks up an account by name, creating it if it does not already exist. Returns the account instance and a boolean indicating if it was newly created. ```go func (s *Server) LookupOrRegisterAccount(name string) (account *Account, isNew bool) ``` -------------------------------- ### Get Subscription Count Source: https://github.com/nats-io/nats-server/blob/main/_autodocs/api-reference/server.md Retrieves the total number of subscriptions across all accounts on the server. This method is useful for monitoring server load and activity. ```go func (s *Server) NumSubscriptions() uint32 ``` -------------------------------- ### Info Struct for Server Connection Details Source: https://github.com/nats-io/nats-server/blob/main/_autodocs/api-reference/server.md Represents the information sent to clients upon connection. Includes server ID, version, host, port, and feature flags like JetStream support. ```go type Info struct { ID string `json:"server_id"` Name string `json:"server_name"` Version string `json:"version"` Proto int `json:"proto"` GitCommit string `json:"git_commit,omitempty"` GoVersion string `json:"go"` Host string `json:"host"` Port int `json:"port"` Headers bool `json:"headers"` AuthRequired bool `json:"auth_required,omitempty"` TLSRequired bool `json:"tls_required,omitempty"` TLSVerify bool `json:"tls_verify,omitempty"` MaxPayload int32 `json:"max_payload"` JetStream bool `json:"jetstream,omitempty"` Cluster string `json:"cluster,omitempty"` ClientConnectURLs []string `json:"connect_urls,omitempty"` LameDuckMode bool `json:"ldm,omitempty"` } ``` -------------------------------- ### Get Number of Remote Leaf Nodes Source: https://github.com/nats-io/nats-server/blob/main/_autodocs/api-reference/server.md Returns the current count of active remote leaf node connections connected to the NATS server. ```go func (s *Server) NumRemotes() int ``` -------------------------------- ### New Server Constructor (Deprecated) Source: https://github.com/nats-io/nats-server/blob/main/_autodocs/api-reference/startup-options.md The legacy constructor for creating a new NATS server instance. It is deprecated in favor of `NewServer` and lacks error handling. ```go func New(opts *Options) *Server ``` -------------------------------- ### Get Goroutine Dump using Curl Source: https://github.com/nats-io/nats-server/blob/main/_autodocs/endpoints.md Command to fetch a goroutine dump from the NATS server's profiling endpoint using curl. ```bash curl http://localhost:6060/debug/pprof/goroutine ``` -------------------------------- ### NATS Server Health Check Source: https://github.com/nats-io/nats-server/blob/main/_autodocs/endpoints.md A simple bash script to check if the NATS server is healthy by sending a GET request to the /healthz endpoint. ```bash #!/bin/bash if curl -s http://localhost:8222/healthz > /dev/null; then echo "Server is healthy" else echo "Server is down" fi ``` -------------------------------- ### Create URL Account Resolver Source: https://github.com/nats-io/nats-server/blob/main/_autodocs/api-reference/accounts.md Initializes a resolver that fetches account JWTs from a specified URL. The endpoint must support a `subject` query parameter and return the JWT in the response body. ```go resolver, err := server.NewURLAccResolver("https://accounts.example.com/lookup") if err != nil { log.Fatal(err) } opts := &server.Options{ AccountResolver: resolver, } ```