appx

package module
v1.5.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 26, 2026 License: MIT Imports: 29 Imported by: 0

README

Appx: Production-Ready Application Container

Go Report Card

中文 | English

appx is a service container designed for building production-grade Go applications.

It is more than just an HTTP/gRPC launcher; it is a lifecycle manager. It orchestrates the startup order, graceful shutdown, health checks, and underlying network enhancements (such as rate limiting, circuit breaking, and HTTP/3) for multiple services (HTTP, gRPC, Background Tasks, Cron).

It deeply integrates netx (network enhancements), o11y (observability), and cert (certificate management), aiming to let you write SRE-standard services with minimal code.

Core Features

  • Unified Lifecycle: Manages the Start/Stop of all components, supporting startup rollbacks and graceful shutdown timeout control.
  • Multi-Protocol:
    • HTTP/1.1 & HTTP/2: Enabled by default.
    • HTTP/3 (QUIC): One-click activation, automatically handles UDP listening and Alt-Svc header injection.
    • gRPC: Integrated with OpenTelemetry interceptors and Panic recovery.
  • Network Enhancements (Powered by netx):
    • Connection Protection: Limits maximum concurrent connections (MaxConns) to prevent OOM.
    • Anti-Slowloris: Automated IO Timeout configuration.
    • High Performance: Supports SO_REUSEPORT to improve multi-core throughput.
  • Zero-Config Observability:
    • Simply pass o11y.Config to automatically inject Tracing middleware, Access Logs, and Metrics.
    • Built-in /healthz and /metrics endpoints.
  • Security Self-Check: Automatically checks for high-risk configurations (e.g., running as Root, weak passwords, file permissions) upon startup.

Installation

go get appx

Quick Start

1. Basic HTTP Service
package main

import (
    "net/http"
    "appx"
    "github.com/rs/zerolog/log"
)

func main() {
    // 1. Create the container
    app := appx.New(appx.WithLogger(&log.Logger))

    // 2. Define business routes
    mux := http.NewServeMux()
    mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        w.Write([]byte("Hello Appx!"))
    })

    // 3. Add HTTP Service
    // Automatically gains: Graceful Shutdown, MaxConns Limit, KeepAlive
    app.Add(appx.NewHttpService("api", ":8080", mux))

    // 4. Run (blocks until interrupt signal)
    if err := app.Run(); err != nil {
        log.Fatal().Err(err).Msg("Appx crashed")
    }
}
func main() {
    // Load config...
    cfg := loadConfig()
    
    // Initialize Observability
    o11y.Init(cfg.O11y)

    // Create container, inject security manager
    app := appx.New(
        appx.WithSecurityManager(security.New(&log.Logger)),
        appx.WithShutdownTimeout(10 * time.Second),
    )

    // --- A. Add Monitor Service (:9090) ---
    // Expose /metrics (Prometheus) and /healthz
    monitorAuth := func(ctx context.Context, user, pass string) (any, error) {
		if user == "admin" && pass == "s3cret" {
			return "admin", nil
		}
		return nil, fmt.Errorf("invalid credentials")
	} // Simple auth middleware
    app.Add(appx.NewMonitorService(":9090", app.HealthHandler(), httpx.AuthBasic(monitorAuth, "Monitor Area")))

    // --- B. Add Main API Service (:8443) ---
    apiSvc := appx.NewHttpService("main-api", ":8443", httpHandler).
        WithMaxConns(10000).        // Rate limiting protection
        WithReusePort().            // Performance optimization
        WithObservability(cfg.O11y) // Auto-inject Trace/Log/Metric

    // Enable HTTPS and HTTP/3
    if certMgr, err := cert.New(cfg.Cert, nil); err == nil {
        apiSvc.WithTLS(certMgr).WithHTTP3()
    }
    app.Add(apiSvc)

    // --- C. Add gRPC Service (:50051) ---
    grpcServer := grpc.NewServer()
    // ... Register PB ...
    app.Add(appx.NewGrpcService("user-rpc", ":50051", grpcServer))

    // --- D. Add Background Tasks ---
    runner := task.NewRunner()
    app.Add(appx.NewTaskService(runner))

    // Start all services
    app.Run()
}

Architecture Design

The Appx uses an Onion Model to build the network layer and provides unified control at the application layer:

graph TD
    Entry[Appx.Run] --> Init[Security Check & Config Dump]
    Init --> S1[Start Service 1]
    Init --> S2[Start Service 2]
    
    subgraph "HttpService / GrpcService"
        L1[net.Listener] --> Netx[netx Middleware]
        Netx --> TLS[TLS / ACME]
        TLS --> O11y[Observability Middleware]
        O11y --> Biz[Business Handler]
    end
    
    S1 --> L1
    
    Entry --> Wait[Wait Signal / Fatal Error]
    Wait --> Stop[Graceful Shutdown - Reverse Order]

Component Details

HttpService

Standard Web service wrapper.

  • WithHTTP3(): Enables QUIC support. Note that HTTP/3 must be used with WithTLS.
  • WithReusePort(): Enables SO_REUSEPORT. Recommended for multi-core environments like Kubernetes.
GrpcService

gRPC service wrapper. Automatically handles net.Listen and enhances connection properties (e.g., timeout control) via netx.

MonitorService

A lightweight HTTP service dedicated to exposing OPS interfaces:

  • /metrics: Prometheus metrics.
  • /healthz: Aggregated status of all registered HealthCheckers.
  • /debug/pprof: Go profiling tools.
TaskService

Integrates github.com/oy3o/task into the Appx lifecycle. Ensures the Appx waits for all background tasks to drain before exiting.

Interface Definition

Implement these to integrate custom components into the Appx:

type Service interface {
    Name() string
    // Non-blocking start
    Start(ctx context.Context) error
    // Blocks until stopped
    Stop(ctx context.Context) error
}

type HealthChecker interface {
    Name() string
    Check(ctx context.Context) error
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Appx

type Appx struct {
	// contains filtered or unexported fields
}

func New

func New(opts ...Option) *Appx

func (*Appx) Add

func (s *Appx) Add(svc Service)

Add 注册服务

func (*Appx) AddHealthChecker

func (s *Appx) AddHealthChecker(checker HealthChecker)

AddHealthChecker 注册健康检查

func (*Appx) AddShutdownHook

func (s *Appx) AddShutdownHook(hook ShutdownHook)

AddShutdownHook 注册关闭钩子

func (*Appx) HealthHandler

func (s *Appx) HealthHandler() http.Handler

HealthHandler 返回一个标准的 http.Handler 用于 /healthz

func (*Appx) Run

func (s *Appx) Run() error

type ErrorNotifiable

type ErrorNotifiable interface {
	SetErrorNotify(ErrorNotifier)
}

ErrorNotifiable 是一个可选接口。 如果 Service 实现了此接口,Appx 会在 Add 时注入一个回调, Service 应在发生致命运行时错误(如 serve crashed)时调用此回调。

type ErrorNotifier

type ErrorNotifier func(error)

ErrorNotifier 定义错误通知回调函数签名

type GrpcService

type GrpcService struct {
	// contains filtered or unexported fields
}

func NewGrpcService

func NewGrpcService(name, addr string, srv *grpc.Server) *GrpcService

func (*GrpcService) Name

func (s *GrpcService) Name() string

func (*GrpcService) SetErrorNotify

func (s *GrpcService) SetErrorNotify(fn ErrorNotifier)

func (*GrpcService) Start

func (s *GrpcService) Start(ctx context.Context) error

func (*GrpcService) Stop

func (s *GrpcService) Stop(ctx context.Context) error

func (*GrpcService) WithLogger

func (s *GrpcService) WithLogger(l *zerolog.Logger) *GrpcService

type HealthChecker

type HealthChecker interface {
	Name() string
	Check(ctx context.Context) error
}

HealthChecker 定义健康检查接口

type HttpService

type HttpService struct {
	// contains filtered or unexported fields
}

HttpService 是一个生产级的 HTTP 服务封装。 它集成了 netx (限流/保活/ReusePort) 和 cert (TLS) 以及 HTTP/3 (QUIC)。

func NewHttpService

func NewHttpService(name, addr string, handler http.Handler) *HttpService

func NewMonitorService

func NewMonitorService(addr string, healthHandler http.Handler, mws ...func(http.Handler) http.Handler) *HttpService

NewMonitorService 创建监控服务。 支持传入 mws 中间件对 /metrics, /healthz, /debug/pprof 进行保护。

示例 - 添加 Basic Auth:

app.Add(server.NewMonitorService(":9090", healthHandler,
  httpx.AuthBasic(myValidator, "Monitor"),
))

func (*HttpService) Name

func (s *HttpService) Name() string

func (*HttpService) SetErrorNotify

func (s *HttpService) SetErrorNotify(fn ErrorNotifier)

SetErrorNotify 实现 ErrorNotifiable 接口

func (*HttpService) Start

func (s *HttpService) Start(ctx context.Context) error

func (*HttpService) Stop

func (s *HttpService) Stop(ctx context.Context) error

func (*HttpService) WithHTTP3

func (s *HttpService) WithHTTP3() *HttpService

WithHTTP3 启用 HTTP/3 (QUIC) 注意:HTTP/3 必须依赖 TLS (WithTLS)。

func (*HttpService) WithKeepAlive

func (s *HttpService) WithKeepAlive(d time.Duration) *HttpService

WithKeepAlive 设置 TCP 保活探测间隔

func (*HttpService) WithLogger

func (s *HttpService) WithLogger(l *zerolog.Logger) *HttpService

WithLogger 设置 Logger

func (*HttpService) WithMaxConns

func (s *HttpService) WithMaxConns(n int) *HttpService

WithMaxConns 设置最大连接数限制

func (*HttpService) WithNetMiddleware

func (s *HttpService) WithNetMiddleware(mws ...netx.Middleware) *HttpService

WithNetMiddleware 注入自定义 TCP 网络层中间件 (如 IP 白名单、Proxy Protocol)

func (*HttpService) WithObservability

func (s *HttpService) WithObservability(cfg o11y.Config) *HttpService

WithObservability 启用自动化可观测性 (Tracing, Metrics, Logging, Panic Recovery) 传入全局 o11y.Config 即可,服务会自动应用 o11y.Handler 中间件。

func (*HttpService) WithReusePort

func (s *HttpService) WithReusePort() *HttpService

WithReusePort 启用端口复用 (SO_REUSEPORT) 允许在多核机器上运行多个进程/线程监听同一端口,由内核进行负载均衡,提升 Accept 吞吐。

func (*HttpService) WithTLS

func (s *HttpService) WithTLS(mgr *cert.Manager) *HttpService

WithTLS 启用 HTTPS

func (*HttpService) WithUDPMiddleware

func (s *HttpService) WithUDPMiddleware(mws ...netx.UDPMiddleware) *HttpService

WithUDPMiddleware 注入自定义 UDP 网络层中间件 (如 PPS 限流)

type Option

type Option func(*Appx)

func WithConfig

func WithConfig(cfg any) Option

WithConfig 注入配置对象,Appx 启动时会打印脱敏后的配置快照

func WithHealthCheckTimeout

func WithHealthCheckTimeout(total, perCheck time.Duration) Option

WithHealthCheckTimeout 设置健康检查的超时时间。 total: 整个健康检查接口的总超时。 perCheck: 单个检查器的超时时间。

func WithLogger

func WithLogger(l *zerolog.Logger) Option

WithLogger 设置自定义 Logger

func WithSecurityManager

func WithSecurityManager(mgr *security.Manager) Option

WithSecurityManager 注入安全检查管理器

func WithShutdownTimeout

func WithShutdownTimeout(d time.Duration) Option

WithShutdownTimeout 设置优雅关闭的超时时间

type Service

type Service interface {
	// Name 返回服务名称,用于日志记录
	Name() string

	// Start 启动服务。
	// 实现注意:
	// 1. 这是一个非阻塞调用(或在内部启动 goroutine)。
	// 2. 如果启动失败,应立即返回 error。
	// 3. 如果服务是阻塞运行的(如 http.Serve),请在实现内部 go func()。
	Start(ctx context.Context) error

	// Stop 优雅停止服务。
	// 实现注意:
	// 1. 这是一个阻塞调用,直到服务完全停止或 ctx 超时。
	// 2. 必须处理 ctx.Done() 以避免永久阻塞。
	Stop(ctx context.Context) error
}

Service 定义了一个可以被 Appx 托管生命周期的组件。 无论是 HTTP Server, gRPC Server, 还是 Task Runner,都必须实现此接口。

func NewTaskService

func NewTaskService(runner *task.Runner) Service

type ShutdownHook

type ShutdownHook func(ctx context.Context) error

ShutdownHook 定义关闭时的清理函数 (如关闭 DB)

type TaskService

type TaskService struct {
	// contains filtered or unexported fields
}

func (*TaskService) Name

func (t *TaskService) Name() string

func (*TaskService) Start

func (t *TaskService) Start(ctx context.Context) error

func (*TaskService) Stop

func (t *TaskService) Stop(ctx context.Context) error

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL