Skip to main content

Getting Started

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 guide is designed for new users who are encountering the Sparrow framework for the first time. It helps you complete environment preparation, project cloning, dependency installation, and configuration in the shortest time possible, and run a minimal viable "Hello World" microservice example. The document also provides common troubleshooting suggestions and multi-platform installation notes to ensure you can get started smoothly.

Project Structure

Sparrow adopts a modular layered architecture with the following core directories and responsibilities:

  • pkg/bootstrap: Application startup, container, HTTP server, and lifecycle management
  • pkg/config: Configuration loading, defaults, and validation
  • pkg/entity/usecase: Domain models and use case layer
  • pkg/adapter/http: HTTP routing and middleware
  • pkg/logger, pkg/messaging, pkg/tasks: Infrastructure including logging, message bus, and task scheduling
  • Root directory: Build and run scripts like go.mod, makefile

Core Components

  • Application Starter App: Responsible for loading configuration, initializing logging, creating Gin engine, starting HTTP server, managing subprocesses, and graceful shutdown
  • IoC Container: Supports anonymous and named dependency registration and resolution, simplifying service assembly
  • Configuration System: Viper loads multiple format configuration files, environment variable overrides, defaults, and validation
  • Domain Entities and Use Cases: Entities like Session, Task and corresponding use case services, embodying the clean architecture core layer

Architecture Overview

The diagram below shows the key flow from startup to HTTP request processing, and the role of configuration and container in it.

Detailed Component Analysis

Application Startup and HTTP Server

  • Initialize configuration and logging
  • Create Gin engine and bind host and port
  • Start subprocesses in background (like subscribers, task schedulers, etc.), with exponential backoff retry on failure
  • Graceful shutdown: Close HTTP server and cleanup resources after receiving signal

IoC Container

  • Supports anonymous and named dependency registration
  • When resolving dependencies, named instances are prioritized, otherwise falls back to anonymous
  • Caches constructed instances to avoid repeated creation

Configuration System

  • Defaults: Application name, version, server address and port, logging, NATS, Redis, Badger, Casbin, SQL, RabbitMQ, etc.
  • Loading Order: Current directory, configs directory, /etc/<app>/, $HOME/.<app>/; supports yaml/yml/json/toml/properties formats
  • Environment Variable Override: AutomaticEnv + SetEnvKeyReplacer converts dots to underscores
  • Validation: Application name non-empty, port range validation

Domain Entities and Use Cases

  • Session Entity: Contains data and expiry time, provides expiry check, update expiry, CRUD data operations
  • Session Use Case Service: Encapsulates business logic for creating, getting, saving, deleting, updating data, clearing expired sessions
  • Task Entity: Task type, status, payload, result, error, priority, retry count, timestamps, etc.
  • Executor Interface: Unified Exec(action) design for easy extension of command/query execution

Dependency Analysis

  • Language and Version: Go 1.25
  • Main Dependencies: Gin (HTTP), Viper (config), Zap (logging), NATS/RabbitMQ/Redis and other middleware ecosystem
  • Build and Run: makefile provides common targets like build/run/test/deps/lint/docker-*

Performance Considerations

  • HTTP Server Timeout: Read/write timeouts and max header size are set in the starter, can be adjusted based on actual scenarios
  • Subprocess Retry: Exponential backoff and max retry count to avoid continuous retry from transient failures
  • Logging and Configuration: Default JSON output and stdout for easy containerization and centralized collection

Troubleshooting Guide

Port Occupied

  • Symptom: Startup fails with port unavailable message
  • Solution: Modify server.port in configuration or release the occupied port
  • Reference: Configuration default port and validation logic

Configuration File Not Taking Effect

  • Symptom: Environment variable override ineffective or defaults not applied
  • Solution: Confirm configuration file format and path, ensure .env is correctly loaded, key names use underscore style
  • Reference: Configuration loading and environment variable replacement

Dependency Injection Resolution Failed

  • Symptom: ResolveByName reports "provider not found"
  • Solution: Confirm Register/RegisterNamed for corresponding constructor, name matches
  • Reference: Container registration and resolution logic

Graceful Shutdown Abnormal

  • Symptom: Resources not released after SIGINT/SIGTERM
  • Solution: Ensure subprocesses are registered through NeedCleanup, check Close implementation
  • Reference: App cleanup process

Conclusion

Through this guide, you have completed environment preparation, project cloning, dependency installation, and configuration setup, and understood the core mechanisms of application startup, configuration loading, and dependency injection. It is recommended to run the minimal example locally first, then gradually integrate your business use cases and entities, finally combining with message bus and task scheduling to achieve a high-cohesion low-coupling microservice architecture.

Appendix

Environment Setup Steps

Install Go 1.25

  • Reference: Go version requirement in module file

Install Necessary Tools

  • Git (clone repository)
  • Make (execute build and run scripts)
  • golangci-lint (optional, code checking)

Install Optional Middleware

  • NATS, Redis, PostgreSQL (based on configuration requirements)

Quick Start Steps

Clone Repository

  • Use Git to clone to local workspace

Install Dependencies

  • Execute make deps (go mod tidy + go mod download)

Verify Installation

  • Execute make test to run unit tests
  • Execute make run or make dev to start service

Configuration Guide

Configuration File Location and Format

  • Supports yaml/yml/json/toml/properties formats
  • Search paths: current directory, ./configs, /etc/<app>/, $HOME/.<app>/

Defaults and Environment Variables

  • Defaults are defined centrally in configuration file
  • Environment variables take effect automatically through AutomaticEnv, key names replaced with underscore style

Key Configuration Items

  • Application: app.name, app.version, app.secret, app.key_path
  • Server: server.host, server.port
  • Logging: log.level, log.format, log.output, log.filename, log.mode
  • NATS: nats.url, nats.stream_name, nats.max_age
  • Redis: redis.host, redis.port, redis.password, redis.db, redis.es_db
  • Badger: badger.data_dir, badger.es_dir, badger.value_threshold, badger.num_compactors, badger.in_memory
  • Casbin: casbin.model_path, casbin.policy_path
  • SQL: sql.driver, sql.host, sql.port, sql.user, sql.password, sql.dbname, sql.es_dbname
  • RabbitMQ: rabbitmq.host, rabbitmq.port, rabbitmq.username, rabbitmq.password, rabbitmq.vhost, rabbitmq.exchange

Minimal "Hello World" Example

The following steps help you create a minimal microservice that only outputs "Hello World":

Create Entry File (e.g., cmd/main.go)

  • Initialize App: Call NewApp and pass necessary options (like ServerPort)
  • Register Route: Mount GET /hello on App.Engine to return "Hello World"
  • Start Service: Call App.Start()

Run

Tips

  • If you need custom port, set server.port in configuration or override via environment variable
  • For logging, middleware, or authentication integration, refer to App's Use options and middleware integration approach

Multi-Platform Installation Notes

macOS/Linux

  • Use package manager to install Go 1.25, Git, Make
  • Optional: Install golangci-lint for static checking

Windows

  • Use official installer to install Go 1.25
  • Use Git Bash or WSL to get Unix-like make experience
  • Note: Configuration file path and environment variable key name replacement rules also apply

Docker

  • Can use make docker-build and make docker-run to build and run containers
  • Note: APP_NAME and APP_VERSION in .env will affect image tags