Skip to main content

Application Startup Process

Table of Contents

  1. Introduction
  2. Project Structure
  3. Core Components
  4. Architecture Overview
  5. Detailed Component Analysis
  6. Dependency Analysis
  7. Performance Considerations
  8. Troubleshooting Guide
  9. Conclusion
  10. Appendix

Introduction

This document systematically explains the application startup process, focusing on the implementation mechanism and startup phases of the NewApp function, including configuration loading, logger initialization, Gin engine creation, service container initialization, subprocess registration and startup, HTTP server startup, and graceful shutdown and resource cleanup. The document also provides startup process sequence diagrams and key code snippet paths to help readers quickly master best practices for startup parameter configuration, environment variable settings, and startup sequence control.

Project Structure

The key modules and responsibilities around the startup process are as follows:

  • Configuration Layer: Responsible for loading configuration from multiple sources, setting default values, environment variable mapping and validation
  • Logging Layer: Selects development or production logging strategy based on configuration, provides unified logging interface
  • Application Layer: Encapsulates App structure, coordinates configuration, logging, container, HTTP engine and subprocesses
  • Container Layer: Provides named/anonymous dependency injection capabilities, supports on-demand instance resolution
  • Option Layer: Assembles database, message bus, middleware, routes, etc. through Option pattern
  • Graceful Shutdown: Unified handling of signals, timeouts and resource cleanup

Core Components

  • App Structure: Carries global configuration, logging, Gin engine, service container, subprocess collection, authentication and scheduler, etc.
  • Container: Supports anonymous and named dependency registration and resolution, has simple dependency injection capability
  • Option System: Assembles database, message bus, middleware, routes, task scheduling, sessions, etc. on-demand through Option functions
  • Graceful Shutdown: Unified handling of signals, timeouts and resource cleanup, ensures subprocesses and subscribers exit orderly

Architecture Overview

Application startup adopts the sequence control of "configuration → logging → container → engine → subprocesses → HTTP server → signal listening", all external dependencies are decoupled and lazily initialized through container.

Detailed Component Analysis

NewApp: Application Initialization and Configuration Loading

  • Configuration Loading: Calls configuration loader, supports multi-format configuration files and environment variable override, automatically sets default values and performs basic validation
  • Logger Initialization: Selects development or production logging strategy based on configuration, provides unified logging interface
  • Application Construction: Creates Gin engine, initializes service container, prepares subprocess collection
  • Name and Version: Reads application name and version from configuration, used for subsequent component identification
  • Option Application: Allows appending configuration items after construction (such as port, host)

Container Initialization and Dependency Injection

  • Supports anonymous and named dependency registration, prioritizes named then anonymous during resolution
  • Dependency resolution uses reflection to call constructor functions, supports recursive resolution of parameter dependencies
  • Provides ResolveInstance and ResolveByName helper methods for convenient resolution by type or name

Option Functions and Extension Points

  • Database: Supports SQLite, Redis, Badger, SQL, etc., registers connection instances through Register
  • Message Bus: Supports NATS JetStream event bus and subscribers, automatically registers and includes in graceful shutdown
  • Middleware: Provides JWT, RSA, RBAC and other middleware, unified integration into Gin engine
  • Routes and Health Check: Registers health check route
  • Task Scheduling: Creates scheduler instance and includes in graceful shutdown
  • Session: Registers memory session storage and session service, and binds routes

Subprocess Registration and Startup

  • Subprocess Registration: Adds components implementing GracefulClose interface to collection through NeedCleanup
  • Startup Phase: Iterates subprocess collection, attempts to start one by one; failures enter exponential backoff retry queue, maximum several retries
  • Retry Mechanism: Uses goroutine with cancel context, exponential backoff (upper limit 1 minute), maximum retry count limit

HTTP Server Startup and Graceful Shutdown

  • Server Creation: Sets read/write timeouts and maximum header size based on configured host and port
  • Startup Method: Starts ListenAndServe in goroutine, captures non-shutdown errors and logs
  • Signal Handling: Listens for SIGINT/SIGTERM, enters graceful shutdown after receiving signal
  • Shutdown Process: Calls Shutdown with 30-second timeout, then executes CleanUp
  • Resource Cleanup: Cancels retry goroutine, calls subprocess Close one by one with 5-second timeout

Configuration Loading Details

  • Configuration Sources: Supports current directory, configs directory, /etc/{appName}/ and $HOME/.{appName}/ paths
  • File Formats: Tries yaml/yml/json/toml/properties/props/prop in order
  • Default Values: Centrally sets default values for each module, reduces environment differences
  • Environment Variables: Automatically reads .env and enables AutomaticEnv, key name replacement rule is dot to underscore
  • Validation Rules: Application name required, port range validation, etc.

Logger Initialization

  • Development Mode: Uses normal debug logging
  • Production Mode: Creates rotating log based on configuration level and output strategy, supports rotation by size and days

Authorization and Middleware

  • Authorization System: Provides token generator and middleware collection, supports named middleware
  • Middleware Assembly: JWT, RSA, RBAC middleware injected into Gin engine through Option

Dependency Analysis

  • App has strong dependencies on configuration, logging, container, Gin engine
  • Option System injects database, message bus, middleware and other external dependencies through Register
  • Subprocess Collection forms closed loop through NeedCleanup and CleanUp, ensures graceful shutdown

Performance Considerations

  • Subprocess retry uses exponential backoff, avoids frequent retry causing resource contention
  • HTTP server sets reasonable read/write timeouts and maximum header size, prevents slow connections from occupying resources
  • Log rotation in production mode rotates by size and days, reduces disk pressure
  • Container resolution only incurs overhead when calling constructor for the first time, subsequent calls reuse cached instances

Troubleshooting Guide

Startup Failure Diagnosis

  • Configuration Loading Failure: Check configuration file path and format, confirm .env exists and key names follow replacement rules
  • Logger Initialization Failure: Confirm log output path is writable, production mode level and format configuration is valid
  • Subprocess Startup Failure: View retry logs, confirm if exponential backoff and maximum retry count are triggered

Graceful Shutdown Issues

  • Server Shutdown Timeout: Check if subprocess Close blocks, appropriately adjust timeout duration
  • Resource Cleanup Exception: Confirm all registered subprocesses implement GracefulClose interface

Common Errors and Suggestions

  • Application Name Empty: Ensure app.name is set in configuration
  • Invalid Port: Ensure server.port is in range 1-65535
  • NATS Connection Failure: Check NATS URL and network connectivity

Conclusion

This document completely outlines the application startup process from configuration loading, logger initialization, container and engine creation, to subprocess registration and startup, HTTP server startup and graceful shutdown. Through option system and container decoupling of external dependencies, combined with exponential backoff retry and timeout control, ensures the startup process is robust and controllable. It is recommended to clearly define configuration sources and environment variable specifications in actual deployment, reasonably set retry and timeout parameters to achieve optimal startup experience and runtime stability.

Appendix

Startup Parameter Configuration Points

  • Configuration File: Supports multiple formats and multi-path search, priority by search order
  • Environment Variables: Automatically reads .env, key name replacement to underscore style
  • Default Values: Centrally set, reduce omissions

Environment Variable Setting Suggestions

  • APP_NAME: Application name, affects configuration search path
  • LOG_MODE: Log mode (dev/prod), determines log output strategy
  • SERVER_HOST/SERVER_PORT: HTTP server bind address and port
  • REDIS_, SQL_, NATS_*: Corresponding external service connection parameters

Startup Sequence Control

  • First configuration then logging, then container and engine, finally subprocesses and HTTP server
  • Components registered through NeedCleanup will be uniformly closed in CleanUp

Startup Failure Handling

  • Record detailed logs, distinguish error types in configuration, connection, startup phases
  • Utilize retry mechanism and timeout control to improve startup success rate