server

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Feb 23, 2026 License: MIT Imports: 11 Imported by: 0

Documentation

Overview

包 server 提供 HTTP/HTTPS 服务器生命周期管理,支持非阻塞启动、 优雅关闭与系统信号监听。

概述

本包通过 Manager 封装 net/http.Server,统一管理监听、服务、 关闭与错误传播流程。支持 HTTP 与 TLS 两种启动模式,内置 SIGINT/SIGTERM 信号处理,适用于生产环境的优雅停机需求。

核心类型

  • Manager:HTTP 服务器管理器,持有 http.Server、net.Listener 与异步错误通道,提供 Start/StartTLS/Shutdown/WaitForShutdown 等生命周期方法。
  • Config:服务器配置,包含监听地址、读写超时、空闲超时、 最大请求头大小与优雅关闭超时。

主要能力

  • 非阻塞启动:Start/StartTLS 在后台 goroutine 中运行服务, 主线程不阻塞。
  • 优雅关闭:Shutdown 在配置的超时内完成请求排空与连接释放。
  • 信号监听:WaitForShutdown 监听 SIGINT/SIGTERM,收到信号后 自动触发优雅关闭流程。
  • 错误传播:Errors() 返回异步错误通道,供调用方监控服务异常。
  • TLS 支持:默认配置 TLS,通过 StartTLS 指定证书与密钥文件。
  • 状态查询:IsRunning/Addr 提供运行状态与监听地址查询。

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Config

type Config struct {
	// 监听地址
	Addr string `yaml:"addr" json:"addr"`

	// 读取超时
	ReadTimeout time.Duration `yaml:"read_timeout" json:"read_timeout"`

	// 写入超时
	WriteTimeout time.Duration `yaml:"write_timeout" json:"write_timeout"`

	// 空闲超时
	IdleTimeout time.Duration `yaml:"idle_timeout" json:"idle_timeout"`

	// 最大请求头大小
	MaxHeaderBytes int `yaml:"max_header_bytes" json:"max_header_bytes"`

	// 优雅关闭超时
	ShutdownTimeout time.Duration `yaml:"shutdown_timeout" json:"shutdown_timeout"`
}

Config 服务器配置

func DefaultConfig

func DefaultConfig() Config

DefaultConfig 返回默认服务器配置

type Manager

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

Manager HTTP 服务器管理器

func NewManager

func NewManager(handler http.Handler, config Config, logger *zap.Logger) *Manager

NewManager 创建服务器管理器

func (*Manager) Addr

func (m *Manager) Addr() string

Addr 返回服务器监听地址

func (*Manager) Errors

func (m *Manager) Errors() <-chan error

Errors returns asynchronous server errors.

func (*Manager) IsRunning

func (m *Manager) IsRunning() bool

IsRunning 检查服务器是否运行中

func (*Manager) Shutdown

func (m *Manager) Shutdown(ctx context.Context) error

Shutdown 优雅关闭服务器

func (*Manager) Start

func (m *Manager) Start() error

Start 启动服务器(非阻塞)

func (*Manager) StartTLS

func (m *Manager) StartTLS(certFile, keyFile string) error

StartTLS 启动 HTTPS 服务器(非阻塞)

func (*Manager) WaitForShutdown

func (m *Manager) WaitForShutdown()

WaitForShutdown 等待关闭信号

Jump to

Keyboard shortcuts

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