### Minimal Application Setup Source: https://github.com/arquivei/go-app/blob/main/_autodocs/INDEX.md Sets up a basic Go application with error recovery and bootstrapping. Use this as a starting point for simple applications. ```go package main import ( "context" "github.com/arquivei/go-app" ) var ( version = "v0.0.0-dev" cfg struct { app.Config } ) func main() { defer app.Recover() app.Bootstrap(version, &cfg) app.RunAndWait(func(ctx context.Context) error { <-ctx.Done() return ctx.Err() }) } ``` -------------------------------- ### Docker Environment Setup Source: https://github.com/arquivei/go-app/blob/main/_autodocs/configuration.md Example Dockerfile to build an application image, generate a default .env file, and run the application with environment variables sourced from the generated file. ```dockerfile FROM golang:1.25 WORKDIR /app COPY . . # Generate configuration RUN go run main.go -app-config-output=env > /app/default.env # Run with environment CMD ["sh", "-c", "set -a && source /app/default.env && go run main.go"] ``` -------------------------------- ### GET /debug/pprof/cmdline Source: https://github.com/arquivei/go-app/blob/main/_autodocs/endpoints.md Retrieves the command line arguments used to start the application. Returns plain text. ```text GET /debug/pprof/cmdline ``` -------------------------------- ### Run Slog Example with Human-Readable Output Source: https://github.com/arquivei/go-app/blob/main/examples/slog/README.md Execute the slog example with human-readable logging enabled. This command is used to start the application and see its default log output. ```sh go run ./examples/slog/ -app-log-human ``` -------------------------------- ### AppConfig Interface Implementation Example Source: https://github.com/arquivei/go-app/blob/main/_autodocs/types.md Provides an example of how to implement the AppConfig interface by embedding app.Config and defining the GetAppConfig method. ```go type MyConfig struct { app.Config Database struct { URL string } } func (c MyConfig) GetAppConfig() Config { return c.Config } ``` -------------------------------- ### GET /debug/pprof/cmdline Source: https://github.com/arquivei/go-app/blob/main/_autodocs/endpoints.md Retrieves the command line arguments used to start the application. Returns plain text with null-separated arguments. ```APIDOC ## GET /debug/pprof/cmdline ### Description Returns the command line arguments used to start the application. ### Method GET ### Endpoint /debug/pprof/cmdline ### Response #### Success Response (200 OK) - **Content-Type**: `text/plain` - **Body**: Null-separated command line arguments ``` -------------------------------- ### Logger Configuration Example Source: https://github.com/arquivei/go-app/blob/main/_autodocs/api-reference/logger.md Demonstrates how logger configuration can be set via command-line flags, environment variables, or struct tags. ```go cfg := struct { app.Config }{} // Configuration can be set via: // 1. Flags: go run main.go -app-log-level=debug -app-log-human=true // 2. Environment: APP_LOG_LEVEL=debug APP_LOG_HUMAN=true go run main.go // 3. Defaults in struct tags ``` -------------------------------- ### Configuration Sources Priority Order Example Source: https://github.com/arquivei/go-app/blob/main/_autodocs/INDEX.md Demonstrates how command-line flags take precedence over environment variables for configuration. This example shows setting APP_LOG_LEVEL via both methods. ```bash # Flags win over environment APP_LOG_LEVEL=info go run main.go -app-log-level=debug # Result: debug (flag takes precedence) ``` -------------------------------- ### Logger Setup with File Output Source: https://github.com/arquivei/go-app/blob/main/_autodocs/api-reference/logger.md Initializes the global logger with a specific configuration, version, and directs logs to both the console and a file. ```go cfg := logger.Config{ Level: "info", Human: true, } // Write logs to console and to a file file, _ := os.Create("app.log") logger.Setup(cfg, "v1.0.0", file) // All logs now include version field // Example output: {"level":"info","version":"v1.0.0","goversion":"go1.25.0","message":"App started"} ``` -------------------------------- ### Configuration Priority Example Source: https://github.com/arquivei/go-app/blob/main/_autodocs/configuration.md Demonstrates how configuration values are loaded in order: flags win over environment variables, which win over default tags, which win over zero values. The example shows a flag value overriding an environment variable. ```bash # Setup HTTP_PORT=9000 go run main.go -http-port=8080 # Resolution: # 1. Flag value: 8080 (wins) # 2. Environment: 9000 # 3. Default tag: (none in this case) # 4. Zero value: "" # Final value: 8080 ``` -------------------------------- ### Bootstrap Application Source: https://github.com/arquivei/go-app/blob/main/_autodocs/api-reference/bootstrap-and-lifecycle.md Initializes the application configuration, logger, and creates the default global app instance. Use this at the start of your main function. ```go var ( version = "v0.0.0-dev" cfg struct { app.Config HTTP struct { Port string `default:"8000"` } Database struct { URL string `default:"postgres://localhost/myapp"` } } ) func main() { defer app.Recover() app.Bootstrap(version, &cfg) // At this point: // - Configuration is loaded // - Logger is initialized // - Admin server is running on :9000 // - Readiness probe is returning "not ready" // - Healthiness probe is returning "ok" // Initialize application dependencies here... app.RunAndWait(mainLoop) } ``` -------------------------------- ### Setup Logger Source: https://github.com/arquivei/go-app/blob/main/_autodocs/api-reference/logger.md Initializes the global logger with the specified configuration, version, and optional additional log writers. ```APIDOC ## Setup ### Description Initializes the global logger with the specified configuration, version, and optional additional log writers. ### Signature ```go func Setup(config Config, version string, extraLogWriters ...io.Writer) ``` ### Parameters - **config** (Config) - Required - Logger configuration (level and format) - **version** (string) - Required - Application version string, included in all log entries - **extraLogWriters** (...io.Writer) - Optional - Additional io.Writer destinations for logs (e.g., files) ### Behavior 1. Configures output format (JSON or human-friendly console) 2. Sets the global log level (trace, debug, info, warn, error, fatal, panic) 3. Adds version and Go version to all log entries as fields 4. Replaces Go's standard log package with zerolog 5. Configures slog (Go's structured logging) to use zerolog 6. Writes logs to stderr by default, plus any extra writers provided ### Example ```go cfg := logger.Config{ Level: "info", Human: true, } // Write logs to console and to a file file, _ := os.Create("app.log") logger.Setup(cfg, "v1.0.0", file) // All logs now include version field // Example output: {"level":"info","version":"v1.0.0","goversion":"go1.25.0","message":"App started"} ``` ``` -------------------------------- ### MainLoopFunc Example Source: https://github.com/arquivei/go-app/blob/main/_autodocs/api-reference/app.md Example implementation of a MainLoopFunc that processes events from a channel and respects context cancellation for shutdown. ```go mainLoop := func(ctx context.Context) error { for { select { case <-ctx.Done(): return ctx.Err() case msg := <-eventChannel: processMessage(msg) } } } app.RunAndWait(mainLoop) ``` -------------------------------- ### New Source: https://github.com/arquivei/go-app/blob/main/_autodocs/api-reference/app.md Creates a new App instance with the specified configuration. It initializes probe groups and the admin server if enabled. Panics if the admin server fails to start. ```APIDOC ## New ### Description Creates a new App instance with the specified configuration. ### Signature ```go func New(c Config) *App ``` ### Parameters #### Path Parameters - **c** (Config) - Required - Configuration struct containing app settings, log level, admin server config, and shutdown behavior ### Returns - **`*App`** — A new App instance with initialized probe groups and admin server (if enabled) ### Throws - Panics if admin server fails to start (logs fatal error) ### Example ```go cfg := app.Config{} cfg.App.Log.Level = "info" cfg.App.AdminServer.Enabled = true cfg.App.AdminServer.Addr = ":9000" myApp := app.New(cfg) ``` ``` -------------------------------- ### Example Usage of ShutdownPriority Source: https://github.com/arquivei/go-app/blob/main/_autodocs/types.md Demonstrates how to create an instance of ShutdownPriority with a specific value. ```go priority := app.ShutdownPriority(100) ``` -------------------------------- ### Kubernetes Readiness Probe Configuration Source: https://github.com/arquivei/go-app/blob/main/_autodocs/endpoints.md Example YAML configuration for a Kubernetes readiness probe. Specifies the HTTP GET endpoint, initial delay, and check intervals. ```yaml readinessProbe: httpGet: path: /ready port: 9000 initialDelaySeconds: 5 periodSeconds: 10 timeoutSeconds: 3 failureThreshold: 3 ``` -------------------------------- ### Run Slog Example with Warn Log Level Source: https://github.com/arquivei/go-app/blob/main/examples/slog/README.md Run the slog example, enabling human-readable output and setting the log level to 'warn'. This demonstrates how changing the log level filters out less critical messages like INFO. ```sh go run ./examples/slog/ -app-log-human -app-log-level=warn ``` -------------------------------- ### Run Godoc Documentation Server Source: https://github.com/arquivei/go-app/blob/main/README.md Starts a local godoc server for viewing project documentation. Open http://localhost:6060 in your browser. ```sh godoc -http=localhost:6060 ``` -------------------------------- ### Prometheus Metrics Example Response Source: https://github.com/arquivei/go-app/blob/main/_autodocs/endpoints.md This snippet shows an example response from the /metrics endpoint, formatted for Prometheus. It displays application metrics such as garbage collection duration. ```text # HELP go_gc_duration_seconds Time spent in garbage collection # TYPE go_gc_duration_seconds summary go_gc_duration_seconds{quantile="0"} 0 go_gc_duration_seconds{quantile="0.25"} 0 ... ``` -------------------------------- ### Recover from Panics in main Source: https://github.com/arquivei/go-app/blob/main/_autodocs/errors.md Use `defer app.Recover()` at the start of main() to catch and log any panics, ensuring graceful application exit. ```go func main() { defer app.Recover() // If any panic occurs in main, it will be caught and logged } ``` -------------------------------- ### GET /debug/pprof/ Source: https://github.com/arquivei/go-app/blob/main/_autodocs/endpoints.md Main pprof index page listing available profiling tools. Returns an HTML page with links to various profiles. ```html /debug/pprof/ /debug/pprof/
Types of profiles available: ... ...
heapheap
goroutinegoroutine
``` -------------------------------- ### Handle Admin Server Startup Failure Source: https://github.com/arquivei/go-app/blob/main/_autodocs/errors.md If the admin server fails to start (e.g., port conflict), adjust the port using `-app-adminserver-addr` or free the existing port. ```go // If port 9000 is already in use: cfg.App.AdminServer.Addr = ":9001" app := app.New(cfg) ``` -------------------------------- ### File Logging Setup Source: https://github.com/arquivei/go-app/blob/main/_autodocs/api-reference/logger.md Configures the logger to write logs to both standard error and a specified file ('app.log'). The logger is set to 'info' level and uses JSON output. ```go logFile, _ := os.Create("app.log") cfg := logger.Config{ Level: "info", Human: false, } logger.Setup(cfg, "v1.0.0", logFile) // Logs go to both stderr and app.log ``` -------------------------------- ### Monitor Admin Server Health Checks Source: https://github.com/arquivei/go-app/blob/main/_autodocs/endpoints.md Command-line examples using curl to check the readiness, healthiness, and retrieve metrics from the admin server. ```bash # Check readiness curl -i http://localhost:9000/ready # Check healthiness curl -i http://localhost:9000/healthy # Get metrics curl http://localhost:9000/metrics ``` -------------------------------- ### Kubernetes Liveness Probe Configuration Source: https://github.com/arquivei/go-app/blob/main/_autodocs/endpoints.md Example YAML configuration for a Kubernetes liveness probe. Similar to readiness probes but with potentially different timing parameters. ```yaml livenessProbe: httpGet: path: /healthy port: 9000 initialDelaySeconds: 10 periodSeconds: 10 timeoutSeconds: 3 failureThreshold: 3 ``` -------------------------------- ### Kubernetes Pod Configuration Source: https://github.com/arquivei/go-app/blob/main/_autodocs/INDEX.md Example Kubernetes Pod configuration for deploying the application. This YAML defines environment variables, ports, and health probes. ```yaml apiVersion: v1 kind: Pod spec: containers: - name: app image: myapp:latest env: - name: APP_ADMINSERVER_ADDR value: ":9000" - name: APP_LOG_LEVEL value: "info" ports: - containerPort: 9000 name: admin - containerPort: 8080 name: http livenessProbe: httpGet: path: /healthy port: admin initialDelaySeconds: 10 periodSeconds: 10 readinessProbe: httpGet: path: /ready port: admin initialDelaySeconds: 5 periodSeconds: 5 ``` -------------------------------- ### Setup Logger with Debug Level and JSON Output Source: https://github.com/arquivei/go-app/blob/main/_autodocs/api-reference/logger.md Configures the logger with a 'debug' level and JSON output format. Messages at or above the 'debug' level will be logged. Debug and trace messages are suppressed if the level is set to 'warn'. ```go // Setup logger with debug level cfg := logger.Config{ Level: "debug", Human: false, // JSON output } logger.Setup(cfg, "v1.0.0") // All these are logged (info, debug, trace are suppressed with warn level) log.Warn().Msg("This is a warning") log.Error().Err(err).Msg("An error occurred") // This is NOT logged (info < warn) log.Info().Msg("This message is skipped") ``` -------------------------------- ### Recovering from Panics in Main Source: https://github.com/arquivei/go-app/blob/main/_autodocs/api-reference/bootstrap-and-lifecycle.md Defers the Recover function at the start of main to catch and log any panics, ensuring they are treated as fatal errors and the application exits cleanly. ```go func main() { defer app.Recover() app.Bootstrap(version, &cfg) app.RunAndWait(mainLoop) } ``` -------------------------------- ### GET /debug/dump/memstats Source: https://github.com/arquivei/go-app/blob/main/_autodocs/endpoints.md Returns detailed memory statistics in a human-readable format. Provides insights into general, heap, stack, and GC statistics. ```text *** General statistics *** Alloc (Alloc): 1048576 bytes [1 mb] Cumulative Alloc (TotalAlloc): 10485760 bytes [10 mb] Obtained from OS (Sys): 52428800 bytes [50 mb] ... *** Heap Memory statistics *** Heap Allocation (HeapAlloc): 1048576 bytes [1 mb] ... ``` -------------------------------- ### Enable Debug Logging Source: https://github.com/arquivei/go-app/blob/main/_autodocs/INDEX.md Enables debug logging and human-readable output for the application. Run this command to get more detailed logs during development. ```bash go run main.go -app-log-level=debug -app-log-human=true ``` -------------------------------- ### Define Custom Configuration Structure Source: https://github.com/arquivei/go-app/blob/main/_autodocs/configuration.md Embed app.Config and define custom fields for HTTP and Database configurations. Custom fields automatically get flags and environment variables. ```go type Config struct { app.Config // Embedded app configuration // Custom fields HTTP struct { Port string `default:"8000"` } Database struct { URL string `default:"postgres://localhost/mydb"` } } func (c Config) GetAppConfig() app.Config { return c.Config } func main() { var cfg Config app.Bootstrap("v1.0.0", &cfg) // Access custom config log.Info().Str("http_port", cfg.HTTP.Port).Msg("Server config") } ``` -------------------------------- ### Container Health Check Configuration Source: https://github.com/arquivei/go-app/blob/main/_autodocs/endpoints.md Dockerfile example demonstrating how to configure container health checks using the admin server's healthiness endpoint. ```dockerfile HEALTHCHECK --interval=10s --timeout=3s --start-period=5s --retries=3 \ CMD curl -f http://localhost:9000/healthy || exit 1 ``` -------------------------------- ### GET /debug/pprof/ Source: https://github.com/arquivei/go-app/blob/main/_autodocs/endpoints.md The main pprof index page lists all available profiling tools. It returns an HTML page with links to different profiling endpoints. ```APIDOC ## GET /debug/pprof/ ### Description Main pprof index page listing available profiling tools. ### Method GET ### Endpoint /debug/pprof/ ### Response #### Success Response (200 OK) - **Content-Type**: `text/html` - **Body**: HTML page with links to available profiles ``` -------------------------------- ### GET /ready Source: https://github.com/arquivei/go-app/blob/main/_autodocs/endpoints.md Kubernetes readiness probe endpoint. Returns 200 OK if all readiness probes are passing, otherwise 500 Internal Server Error. It lists failed probes in the response body. ```APIDOC ## GET /ready ### Description Kubernetes readiness probe endpoint. Returns 200 OK if all readiness probes are passing, otherwise 500 Internal Server Error. It lists failed probes in the response body. ### Method GET ### Endpoint /ready ### Parameters #### Query Parameters - None ### Response #### Success Response (200) - **Content-Type**: `text/plain` - **Body**: `readiness:OK` #### Error Response (500) - **Content-Type**: `text/plain` - **Body**: `readiness:probe1,probe2` (comma-separated list of failed probes) ### Example Responses ``` HTTP/1.1 200 OK Content-Length: 12 readiness:OK ``` ``` HTTP/1.1 500 Internal Server Error Content-Length: 28 readiness:database,cache ``` ``` -------------------------------- ### Register Shutdown Handler with Timeout Source: https://github.com/arquivei/go-app/blob/main/_autodocs/configuration.md Example of registering a shutdown handler with a specific timeout. The global shutdown timeout should be set slightly longer than the sum of all handler timeouts. ```go // Handler timeout: 5 seconds app.RegisterShutdownHandler(&app.ShutdownHandler{ Name: "database", Handler: db.Close, Timeout: 5 * time.Second, Priority: app.ShutdownPriority(100), }) // Global timeout: 10 seconds (sum of all handlers + buffer) cfg.App.Shutdown.Timeout = 10 * time.Second ``` -------------------------------- ### Safe Shutdown Handler Implementation Source: https://github.com/arquivei/go-app/blob/main/_autodocs/errors.md Provides an example of implementing a safe shutdown handler that uses a goroutine and a select statement to manage potential timeouts or context cancellations during cleanup operations. ```go func safeShutdown(ctx context.Context) error { done := make(chan error, 1) go func() { done <- myCleanup() }() select { case err := <-done: return err case <-ctx.Done(): // Handle timeout or cancellation return ctx.Err() } } app.RegisterShutdownHandler(&app.ShutdownHandler{ Name: "my_service", Handler: safeShutdown, Policy: app.ErrorPolicyAbort, Priority: app.ShutdownPriority(100), Timeout: 5 * time.Second, }) ``` -------------------------------- ### Probe Check Failure Example Source: https://github.com/arquivei/go-app/blob/main/_autodocs/errors.md Illustrates an HTTP 500 response from the /ready endpoint indicating a probe failure, with the response body listing the failed probe. ```bash $ curl -i http://localhost:9000/ready HTTP/1.1 500 Internal Server Error Content-Length: 21 readiness:database ``` -------------------------------- ### Command Line Argument for Log Level Source: https://github.com/arquivei/go-app/blob/main/_autodocs/errors.md Demonstrates how to set an invalid log level via command line argument, which causes a panic. Also shows a valid example. ```bash # Invalid go run main.go -app-log-level=invalid # Output: panic: Unknown Level String: 'invalid' # Valid go run main.go -app-log-level=debug ``` -------------------------------- ### GET /debug/dump/memory Source: https://github.com/arquivei/go-app/blob/main/_autodocs/endpoints.md Returns a heap profile showing memory allocations in pprof format. Use curl to download and go tool pprof to analyze. ```bash curl http://localhost:9000/debug/dump/memory > heap.prof go tool pprof heap.prof ``` -------------------------------- ### GET /debug/pprof/profile with seconds parameter Source: https://github.com/arquivei/go-app/blob/main/_autodocs/endpoints.md CPU profiler endpoint. Collects CPU profile data for a specified duration. Use the 'seconds' query parameter to set the duration. ```bash # Profile for 30 seconds and save to file go tool pprof http://localhost:9000/debug/pprof/profile?seconds=30 # Or download with curl curl http://localhost:9000/debug/pprof/profile?seconds=30 > cpu.prof go tool pprof cpu.prof ``` -------------------------------- ### Kubernetes Readiness Probe - Success Response Source: https://github.com/arquivei/go-app/blob/main/_autodocs/endpoints.md Example of a successful response from the /ready endpoint, indicating all readiness probes are passing. This is used by Kubernetes to determine if an application is ready to receive traffic. ```http HTTP/1.1 200 OK Content-Length: 12 readiness:OK ``` -------------------------------- ### RunAndWait Source: https://github.com/arquivei/go-app/blob/main/_autodocs/api-reference/bootstrap-and-lifecycle.md Executes the main application loop and waits for termination signal or main loop completion. It sets the readiness probe to OK, starts the main loop, waits for signals or loop completion, and manages graceful shutdown. ```APIDOC ## RunAndWait ### Description Executes the main application loop and waits for termination signal or main loop completion. ### Signature ```go func RunAndWait[T func() | func() error | func(context.Context) | func(context.Context) error](f T) ``` ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Parameters - **f** (func (4 overloads)) - Required - Main loop function matching one of the supported signatures. Will be called to initialize the readiness probe ### Returns - None (blocks until application shutdown completes, then calls os.Exit) ### Throws - Panics if Bootstrap was not called (default app not initialized) - Panics if called more than once on the same app instance - May call os.Exit(1) if main loop returns error or shutdown fails ### Function Overloads The function parameter can have any of these signatures: 1. `func()` — Simple function with no parameters 2. `func() error` — Function returning error 3. `func(context.Context)` — Function receiving cancellation context 4. `func(context.Context) error` — Function receiving context and returning error ### Behavior 1. Sets readiness probe to OK 2. Starts the main loop on a separate goroutine 3. Waits for either: - SIGINT or SIGTERM signal - Main loop function to return 4. Sets readiness probe to not OK 5. Waits for grace period (default 3s) before shutdown 6. Executes all registered shutdown handlers in priority order 7. Sets healthiness probe to not OK (forces pod restart) 8. Exits with code 0 on success, code 1 on error ### Example - Simple Function ```go app.RunAndWait(func() { log.Info().Msg("App started") // Do something... }) ``` ### Example - With Context ```go app.RunAndWait(func(ctx context.Context) error { for { select { case <-ctx.Done(): return ctx.Err() case event := <-eventChan: processEvent(event) } } }) ``` ### Example - With Error Handling ```go app.RunAndWait(func() error { err := initializeServices() if err != nil { return fmt.Errorf("failed to initialize: %w", err) } return httpServer.ListenAndServe() }) ``` ### Example - HTTP Server with Shutdown Handler ```go func main() { defer app.Recover() app.Bootstrap(version, &cfg) httpServer := &http.Server{ Addr: ":8080", Handler: mux, ReadHeaderTimeout: 10 * time.Second, } app.RegisterShutdownHandler(&app.ShutdownHandler{ Name: "http_server", Handler: httpServer.Shutdown, Policy: app.ErrorPolicyAbort, Priority: app.ShutdownPriority(100), Timeout: 5 * time.Second, }) app.RunAndWait(httpServer.ListenAndServe) } ``` ``` -------------------------------- ### Bootstrap Source: https://github.com/arquivei/go-app/blob/main/_autodocs/api-reference/bootstrap-and-lifecycle.md Initializes the configuration, sets up the logger, and creates the default global app instance. It parses configuration, initializes the logger, sets up log output, creates the app instance with an admin server if enabled, and may execute probe checks. ```APIDOC ## Bootstrap ### Description Initializes the configuration, sets up the logger, and creates the default global app instance. ### Signature ```go func Bootstrap(appVersion string, config AppConfig) ``` ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Parameters - **appVersion** (string) - Required - Version string (e.g., "v1.0.0"). Included in all log entries and probe responses - **config** (AppConfig) - Required - Configuration struct that embeds app.Config. Must implement GetAppConfig() method ### Throws - Calls log.Fatal() if configuration parsing fails - Calls os.Exit(0) if config output format is specified (--app-config-output) ### Behavior 1. Parses configuration from flags, environment variables, and defaults 2. Initializes the zerolog logger with configured level (trace/debug/info/warn/error/fatal/panic) 3. Sets up log output format (JSON or human-readable) 4. Creates the default global app with admin server (if enabled) 5. May execute probe checks and exit if --app-check-ready or --app-check-healthy flags are set ### Example ```go var ( version = "v0.0.0-dev" cfg struct { app.Config HTTP struct { Port string `default:"8000"` } Database struct { URL string `default:"postgres://localhost/myapp"` } } ) func main() { defer app.Recover() app.Bootstrap(version, &cfg) // At this point: // - Configuration is loaded // - Logger is initialized // - Admin server is running on :9000 // - Readiness probe is returning "not ready" // - Healthiness probe is returning "ok" // Initialize application dependencies here... app.RunAndWait(mainLoop) } ``` ``` -------------------------------- ### Custom Field Environment Variables Example Source: https://github.com/arquivei/go-app/blob/main/_autodocs/configuration.md Custom configuration fields can be set via environment variables using uppercase with underscores. Ensure to set other app environment variables like APP_LOG_LEVEL as needed. ```bash HTTP_PORT=8080 \ DATABASE_URL="postgres://prod-db/app" \ APP_LOG_LEVEL=debug \ go run main.go ``` -------------------------------- ### GET /debug/pprof/trace with seconds parameter Source: https://github.com/arquivei/go-app/blob/main/_autodocs/endpoints.md Execution trace endpoint. Captures Go execution trace data for a specified duration. Use the 'seconds' query parameter to set the duration. ```bash curl http://localhost:9000/debug/pprof/trace?seconds=5 > trace.out go tool trace trace.out ``` -------------------------------- ### Validate Configuration with Custom Values Source: https://github.com/arquivei/go-app/blob/main/_autodocs/configuration.md Validate configuration by providing custom values, including invalid ones, to check error handling. The example shows an invalid port value causing a parsing error. ```bash # Check with custom values HTTP_PORT=invalid go run main.go # Output: error parsing HTTP.Port: invalid value ``` -------------------------------- ### Kubernetes ConfigMap Integration Source: https://github.com/arquivei/go-app/blob/main/_autodocs/configuration.md Example Kubernetes ConfigMap and Pod definitions for integrating application configuration. The ConfigMap provides environment variables, and the Pod uses envFrom to load them, along with defining liveness and readiness probes. ```yaml apiVersion: v1 kind: ConfigMap metadata: name: app-config data: APP_LOG_LEVEL: "info" APP_LOG_HUMAN: "false" APP_ADMINSERVER_ADDR: ":9000" APP_SHUTDOWN_GRACEPERIOD: "10s" APP_SHUTDOWN_TIMEOUT: "15s" --- apiVersion: v1 kind: Pod metadata: name: app spec: containers: - name: app image: myapp:latest envFrom: - configMapRef: name: app-config livenessProbe: httpGet: path: /healthy port: 9000 initialDelaySeconds: 10 readinessProbe: httpGet: path: /ready port: 9000 initialDelaySeconds: 5 ``` -------------------------------- ### New App Constructor Source: https://github.com/arquivei/go-app/blob/main/_autodocs/api-reference/app.md Creates a new App instance with the specified configuration. Ensure the configuration struct is properly initialized. ```go cfg := app.Config{} cfg.App.Log.Level = "info" cfg.App.AdminServer.Enabled = true cfg.App.AdminServer.Addr = ":9000" myApp := app.New(cfg) ``` -------------------------------- ### Initialize Default App Before RunAndWait Source: https://github.com/arquivei/go-app/blob/main/_autodocs/errors.md Always call `Bootstrap()` before using package-level functions like `RunAndWait()` to prevent panics. ```go func main() { defer app.Recover() // Missing: app.Bootstrap(version, &cfg) app.RunAndWait(mainLoop) // Panics! } ``` -------------------------------- ### Basic Go App Initialization and Run Source: https://github.com/arquivei/go-app/blob/main/README.md This snippet shows a minimal Go program that compiles and runs with all app features, including lifecycle and graceful shutdown. It initializes the app with a version and configuration, then runs a task that waits for context cancellation. ```go package main import ( "context" "github.com/arquivei/go-app" ) var ( version = "v0.0.0-dev" cfg struct { app.Config } ) func main() { defer app.Recover() app.Bootstrap(version, &cfg) app.RunAndWait(func(ctx context.Context) error { <-ctx.Done() return ctx.Err() }) } ``` -------------------------------- ### Typical Go Application Lifecycle Flow Source: https://github.com/arquivei/go-app/blob/main/_autodocs/api-reference/bootstrap-and-lifecycle.md Illustrates a standard application flow including bootstrapping, dependency initialization, shutdown handler registration, probe creation, and running the main application loop with graceful shutdown handling. ```go func main() { defer app.Recover() // Catch any panics // 1. Bootstrap: Load config, setup logger, create app app.Bootstrap(version, &cfg) // - Config is loaded from flags/env/defaults // - Logger is initialized // - Admin server starts on :9000 // - Readiness probe: NOT READY // - Healthiness probe: OK // 2. Initialize dependencies db, err := initializeDatabase() if err != nil { log.Fatal().Err(err).Msg("Failed to init database") } // 3. Register shutdown handlers app.RegisterShutdownHandler(&app.ShutdownHandler{ Name: "database", Handler: db.Close, Policy: app.ErrorPolicyAbort, Priority: app.ShutdownPriority(100), Timeout: 5 * time.Second, }) // 4. Create probes for dependencies dbProbe, _ := app.ReadinessProbeGroup().NewProbe("database", true) // 5. Run the main loop app.RunAndWait(func(ctx context.Context) error { // - Readiness probe becomes OK log.Info().Msg("Application ready to serve") // Main logic here... for { select { case <-ctx.Done(): // Graceful shutdown initiated return ctx.Err() case work := <-workChan: processWork(work) } } }) // Function returns here when shutdown completes } ``` -------------------------------- ### GET /metrics Source: https://github.com/arquivei/go-app/blob/main/_autodocs/endpoints.md Returns Prometheus-format metrics about the application. This endpoint is controlled by `Config.App.AdminServer.With.Metrics` and can be disabled. ```APIDOC ## GET /metrics ### Description Returns Prometheus-format metrics about the application. ### Method GET ### Endpoint /metrics ### Parameters #### Query Parameters - None ### Response #### Success Response (200) - **Content-Type**: `text/plain; version=0.0.4; charset=utf-8` - **Body**: Prometheus metrics in text format ### Request Example ``` # HELP go_gc_duration_seconds Time spent in garbage collection # TYPE go_gc_duration_seconds summary go_gc_duration_seconds{quantile="0"} 0 go_gc_duration_seconds{quantile="0.25"} 0 ... ``` ``` -------------------------------- ### GET /debug/pprof/trace Source: https://github.com/arquivei/go-app/blob/main/_autodocs/endpoints.md Returns an execution trace for a specified duration. Useful for analyzing application performance and identifying bottlenecks. ```APIDOC ## GET /debug/pprof/trace ### Description Returns an execution trace for the specified duration. ### Method GET ### Endpoint /debug/pprof/trace ### Query Parameters #### Query Parameters - **seconds** (int) - Optional - Duration of trace collection in seconds (default: 1) ### Response #### Success Response (200 OK) - **Content-Type**: `application/octet-stream` - **Body**: Go execution trace data ### Request Example ```bash curl http://localhost:9000/debug/pprof/trace?seconds=5 > trace.out go tool trace trace.out ``` ``` -------------------------------- ### Create and Configure Probe Groups Source: https://github.com/arquivei/go-app/blob/main/_autodocs/api-reference/probe.md Initialize ProbeGroup instances for readiness and healthiness checks. Create individual probes within these groups and update their status as services become available or degrade. ```go // Create probes readinessGroup := app.NewProbeGroup("readiness") healthinessGroup := app.NewProbeGroup("healthiness") // Create individual probes dbProbe, _ := readinessGroup.NewProbe("database", false) cacheProbe, _ := readinessGroup.NewProbe("cache", false) // Later, when services are ready dbProbe.SetOk() cacheProbe.SetOk() // Kubernetes liveness probe checks /healthy endpoint // Kubernetes readiness probe checks /ready endpoint ``` -------------------------------- ### GET /debug/dump/goroutines Source: https://github.com/arquivei/go-app/blob/main/_autodocs/endpoints.md Returns a dump of all goroutines and their stack traces. Useful for diagnosing deadlocks or excessive goroutine usage. ```text goroutine 1 [running]: runtime/debug.Stack(0x0, 0x0, 0x0) /usr/local/go/src/runtime/debug/stack.go:24 +0x90 main.dumpGoroutines(0x14000196000, 0x14000196000) /app/httphandler_dump.go:13 +0x24 ... ``` -------------------------------- ### GET /debug/dump/goroutines Source: https://github.com/arquivei/go-app/blob/main/_autodocs/endpoints.md Returns a dump of all goroutines and their current stack traces. Helpful for debugging deadlocks or unexpected application behavior. ```APIDOC ## GET /debug/dump/goroutines ### Description Returns a dump of all goroutines and their stack traces. ### Method GET ### Endpoint /debug/dump/goroutines ### Response #### Success Response (200 OK) - **Content-Type**: `text/plain` - **Body**: Complete stack trace of all goroutines ``` -------------------------------- ### GET /debug/pprof/profile Source: https://github.com/arquivei/go-app/blob/main/_autodocs/endpoints.md The CPU profiler endpoint. Collects CPU profile data for a specified duration and returns it in pprof format. ```APIDOC ## GET /debug/pprof/profile ### Description CPU profiler endpoint. Returns CPU profile data for the specified duration. ### Method GET ### Endpoint /debug/pprof/profile ### Query Parameters #### Query Parameters - **seconds** (int) - Optional - Duration of profile collection in seconds (default: 30) ### Response #### Success Response (200 OK) - **Content-Type**: `application/octet-stream` - **Body**: pprof format CPU profile data ### Request Example ```bash go tool pprof http://localhost:9000/debug/pprof/profile?seconds=30 # Or download with curl curl http://localhost:9000/debug/pprof/profile?seconds=30 > cpu.prof go tool pprof cpu.prof ``` ``` -------------------------------- ### GET /debug/dump/memory Source: https://github.com/arquivei/go-app/blob/main/_autodocs/endpoints.md Returns a heap profile detailing memory allocations. This can be used to identify memory leaks or excessive memory usage. ```APIDOC ## GET /debug/dump/memory ### Description Returns a heap profile showing memory allocations. ### Method GET ### Endpoint /debug/dump/memory ### Response #### Success Response (200 OK) - **Content-Type**: `application/octet-stream` - **Body**: pprof format heap profile #### Error Response (500 Internal Server Error) - **Body**: Indicates failure if heap profile write fails or heap buffer is empty. ### Request Example ```bash curl http://localhost:9000/debug/dump/memory > heap.prof go tool pprof heap.prof ``` ``` -------------------------------- ### Creating a Readiness Probe Source: https://github.com/arquivei/go-app/blob/main/_autodocs/api-reference/bootstrap-and-lifecycle.md Creates a new probe for the readiness probe group. This probe indicates whether the application is ready to serve traffic. The second return value indicates if the probe is enabled. ```go readyProbe, _ := app.ReadinessProbeGroup().NewProbe("database", false) ``` -------------------------------- ### Print Configuration as YAML Source: https://github.com/arquivei/go-app/blob/main/_autodocs/configuration.md Output the current application configuration in YAML format. This is helpful for visualizing the configuration structure and debugging. ```bash go run main.go -app-config-output=yaml # Output: # app: # log: # level: info # human: false # adminserver: # enabled: true # addr: localhost:9000 # ... ``` -------------------------------- ### Set Log Level via Flag, Environment, or Code Source: https://github.com/arquivei/go-app/blob/main/_autodocs/configuration.md Demonstrates how to set the minimum log level using command-line flags, environment variables, or directly in code before bootstrapping the application. ```bash # Via flag go run main.go -app-log-level=debug # Via environment APP_LOG_LEVEL=debug go run main.go # Via code (before Bootstrap) var cfg struct { app.Config } cfg.App.Log.Level = "debug" app.Bootstrap("v1.0.0", &cfg) ``` -------------------------------- ### Disable Admin Server Source: https://github.com/arquivei/go-app/blob/main/_autodocs/configuration.md Example of how to disable the admin server, which provides metrics, health probes, and debug endpoints, using a command-line flag. ```bash go run main.go -app-adminserver-enabled=false ``` -------------------------------- ### AppConfig Interface Implementation Source: https://github.com/arquivei/go-app/blob/main/_autodocs/api-reference/bootstrap-and-lifecycle.md Demonstrates the implementation pattern for the AppConfig interface, which provides access to application configuration. The GetAppConfig method should return the configuration struct. ```go type Config struct { app.Config HTTP struct { Port string } } func (c Config) GetAppConfig() Config { // Return the embedded app.Config return c } ``` -------------------------------- ### Print Application Configuration Source: https://github.com/arquivei/go-app/blob/main/_autodocs/INDEX.md Prints the application's configuration in different formats (environment variables, JSON, YAML). Use these commands to inspect your configuration. ```bash # As environment variables go run main.go -app-config-output=env # As JSON go run main.go -app-config-output=json # As YAML go run main.go -app-config-output=yaml ``` -------------------------------- ### Run Application with Simple Function Source: https://github.com/arquivei/go-app/blob/main/_autodocs/api-reference/bootstrap-and-lifecycle.md Executes the main application loop using a simple function. This is suitable for tasks that do not require context or error handling. ```go app.RunAndWait(func() { log.Info().Msg("App started") // Do something... }) ``` -------------------------------- ### Custom Field Flags Example Source: https://github.com/arquivei/go-app/blob/main/_autodocs/configuration.md Custom configuration fields automatically generate flags based on their struct path. Use double-hyphenated names for flags. ```bash go run main.go \ -http-port=8080 \ -database-url="postgres://prod-db/app" ``` -------------------------------- ### Run Application with Context and Error Handling Source: https://github.com/arquivei/go-app/blob/main/_autodocs/api-reference/bootstrap-and-lifecycle.md Executes the main application loop with a function that accepts a context and returns an error. This allows for graceful cancellation and error reporting. ```go app.RunAndWait(func(ctx context.Context) error { for { select { case <-ctx.Done(): return ctx.Err() case event := <-eventChan: processEvent(event) } } }) ``` -------------------------------- ### Generate .env File Source: https://github.com/arquivei/go-app/blob/main/_autodocs/configuration.md Use the -app-config-output=env flag to generate a .env file containing default configuration values. ```bash go run main.go -app-config-output=env > .env ``` -------------------------------- ### Get Error Policy String Representation Source: https://github.com/arquivei/go-app/blob/main/_autodocs/api-reference/shutdown-handler.md Converts an ErrorPolicy constant to its string representation. Useful for logging or debugging to understand the policy applied to an error. ```go policyStr := app.ErrorPolicyString(app.ErrorPolicyAbort) // policyStr = "abort" ``` -------------------------------- ### Print Configuration as Environment Variables Source: https://github.com/arquivei/go-app/blob/main/_autodocs/configuration.md Use this flag to output the current application configuration as environment variables. This is useful for debugging and generating .env files. ```bash go run main.go -app-config-output=env # Output: # APP_LOG_LEVEL=info # APP_LOG_HUMAN= # APP_ADMINSERVER_ENABLED=true # APP_ADMINSERVER_ADDR=localhost:9000 # APP_ADMINSERVER_WITH_DEBUGURLS=true # APP_ADMINSERVER_WITH_METRICS=true # APP_ADMINSERVER_WITH_PROBES=true # APP_SHUTDOWN_GRACEPERIOD=3s # APP_SHUTDOWN_TIMEOUT=5s ``` ```bash go run main.go -app-config-output=env > .env source .env go run main.go ``` -------------------------------- ### Configure and Run Application with Shutdown Handlers Source: https://github.com/arquivei/go-app/blob/main/_autodocs/api-reference/shutdown-handler.md Configures application shutdown grace period and timeout, then registers multiple handlers with specific policies, priorities, and timeouts. Finally, runs the application. ```go cfg := app.Config{} cfg.App.Shutdown.GracePeriod = 3 * time.Second // Wait 3s before shutdown cfg.App.Shutdown.Timeout = 5 * time.Second // All handlers must finish in 5s app := app.New(cfg) // Register handlers app.RegisterShutdownHandler(&app.ShutdownHandler{ Name: "http_server", Handler: httpServer.Shutdown, Policy: app.ErrorPolicyAbort, Priority: app.ShutdownPriority(100), Timeout: 3 * time.Second, }) app.RegisterShutdownHandler(&app.ShutdownHandler{ Name: "database", Handler: db.Close, Policy: app.ErrorPolicyWarn, Priority: app.ShutdownPriority(50), Timeout: 2 * time.Second, }) app.RunAndWait(mainLoop) ``` -------------------------------- ### Print Default Configuration in Environment Variable Format Source: https://github.com/arquivei/go-app/blob/main/README.md Use this command to print the default application configuration in environment variable format. This is useful for understanding available settings and their default values. ```text go run . -app-config-output=env ``` -------------------------------- ### Production Configuration Recommendations Source: https://github.com/arquivei/go-app/blob/main/_autodocs/configuration.md Recommended configuration settings for development and production environments, highlighting differences in log levels, human-readable logs, and admin server settings. ```yaml # Development APP_LOG_LEVEL: debug APP_LOG_HUMAN: "true" APP_ADMINSERVER_WITH_DEBUGURLS: "true" # Production APP_LOG_LEVEL: info APP_LOG_HUMAN: "false" APP_ADMINSERVER_WITH_DEBUGURLS: "false" APP_SHUTDOWN_GRACEPERIOD: 10s APP_SHUTDOWN_TIMEOUT: 15s ``` -------------------------------- ### GET /debug/dump/memstats Source: https://github.com/arquivei/go-app/blob/main/_autodocs/endpoints.md Provides detailed memory statistics in a human-readable format, covering general, heap, stack, and off-heap memory usage, as well as garbage collector statistics. ```APIDOC ## GET /debug/dump/memstats ### Description Returns detailed memory statistics in human-readable format. ### Method GET ### Endpoint /debug/dump/memstats ### Response #### Success Response (200 OK) - **Content-Type**: `text/plain` - **Body**: Detailed memory statistics ### Content Sections - General statistics — Overall memory usage - Heap Memory statistics — Heap-specific allocation - Stack Memory statistics — Stack allocation - Off-heap Memory statistics — cgo, profiling, GC metadata - Garbage Collector statistics — GC cycles and pauses ``` -------------------------------- ### JSON Logging Configuration for Production Source: https://github.com/arquivei/go-app/blob/main/_autodocs/api-reference/logger.md Sets up the logger for production environments with 'info' level and JSON output. Only messages with 'info' level or higher will be logged. This format is suitable for machine parsing. ```go cfg := logger.Config{ Level: "info", // Only info and above Human: false, // JSON format for machine parsing } logger.Setup(cfg, "v1.0.0") // Logs are emitted as JSON log.Info().Str("user_id", "123").Msg("User logged in") // Output: {"level":"info","version":"v1.0.0","goversion":"go1.25.0","user_id":"123","message":"User logged in"} ``` -------------------------------- ### Fix Missing AppConfig Implementation Source: https://github.com/arquivei/go-app/blob/main/_autodocs/errors.md Ensure your config struct embeds `app.Config` or implements `GetAppConfig()` to avoid bootstrap panics. ```go // Wrong - missing GetAppConfig method type Config struct { app.Config HTTP struct{ Port string } } app.Bootstrap("v1.0.0", &Config{}) // Will fail ``` ```go type Config struct { app.Config HTTP struct{ Port string } } func (c Config) GetAppConfig() app.Config { return c.Config } app.Bootstrap("v1.0.0", &Config{}) // Works ``` -------------------------------- ### Kubernetes Healthiness Probe - Failure Response Source: https://github.com/arquivei/go-app/blob/main/_autodocs/endpoints.md Example of a failing response from the /healthy endpoint, listing the probes that did not pass. Kubernetes may restart the application pod if this response is received. ```http HTTP/1.1 500 Internal Server Error Content-Length: 21 healthiness:deadlock ``` -------------------------------- ### Kubernetes Readiness Probe - Failure Response Source: https://github.com/arquivei/go-app/blob/main/_autodocs/endpoints.md Example of a failing response from the /ready endpoint, listing the probes that did not pass. Kubernetes will stop sending traffic to the application when this response is received. ```http HTTP/1.1 500 Internal Server Error Content-Length: 28 readiness:database,cache ``` -------------------------------- ### Load Environment File Source: https://github.com/arquivei/go-app/blob/main/_autodocs/configuration.md Load environment variables from a .env file using 'source .env' or 'export $(cat .env | xargs)' before running the application. ```bash # Bash set -a source .env set +a go run main.go # Or with environment variables export $(cat .env | xargs) go run main.go ``` -------------------------------- ### Register Shutdown Handlers Source: https://github.com/arquivei/go-app/blob/main/_autodocs/api-reference/shutdown-handler.md Demonstrates registering shutdown handlers with names, handler functions, and priorities. Ensure handlers are registered with appropriate priorities for orderly shutdown. ```go app.RegisterShutdownHandler(&app.ShutdownHandler{ Name: "http", Handler: httpServer.Shutdown, Priority: PriorityHTTPServer, }) app.RegisterShutdownHandler(&app.ShutdownHandler{ Name: "database", Handler: db.Close, Priority: PriorityDatabase, }) app.RegisterShutdownHandler(&app.ShutdownHandler{ Name: "cache", Handler: cache.Close, Priority: PriorityCache, }) ``` -------------------------------- ### Kubernetes Healthiness Probe - Success Response Source: https://github.com/arquivei/go-app/blob/main/_autodocs/endpoints.md Example of a successful response from the /healthy endpoint, indicating the application is alive and all healthiness probes are passing. Kubernetes uses this to monitor application liveness. ```http HTTP/1.1 200 OK Content-Length: 13 healthiness:OK ``` -------------------------------- ### Validate Configuration Defaults Source: https://github.com/arquivei/go-app/blob/main/_autodocs/configuration.md Check default configuration values by outputting them in YAML format using the -app-config-output=yaml flag. ```bash # Check default values go run main.go -app-config-output=yaml ``` -------------------------------- ### Default Configuration in Environment Variable Format Source: https://github.com/arquivei/go-app/blob/main/README.md This output displays the default configuration of the application in environment variable format. Each line represents a configurable setting and its default value. ```text APP_LOG_LEVEL=info APP_LOG_HUMAN= APP_ADMINSERVER_ENABLED=true APP_ADMINSERVER_ADDR=localhost:9000 APP_ADMINSERVER_WITH_DEBUGURLS=true APP_ADMINSERVER_WITH_METRICS=true APP_ADMINSERVER_WITH_PROBES=true APP_SHUTDOWN_GRACEPERIOD=3s APP_SHUTDOWN_TIMEOUT=5s APP_CONFIG_OUTPUT= ```