appsrv

package
v0.2.4 Latest Latest
Warning

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

Go to latest
Published: Nov 12, 2026 License: MIT Imports: 15 Imported by: 0

Documentation

Overview

Package appsrv 负责以「库函数调用」方式启动 gobrave 后端服务。

它把原 main.go 里的启动逻辑(加载配置 → 构建依赖注入容器 → 监听端口 → 优雅退出)抽取为可复用的 Server 类型,使命令行入口(main.go)与 桌面入口(cmd/desktop)共用同一套代码:

srv, err := appsrv.New(appsrv.Options{})
if err != nil { ... }
if err := srv.Start(ctx); err != nil { ... }
...
srv.Shutdown(context.Background())

这样桌面端无需拉起子进程,后端与窗口在同一进程内运行, 退出时也能保证顺序关闭(先关窗口,再停服务)。

Index

Constants

View Source
const (
	// DefaultHost 是未配置 server.host 时的监听地址。
	DefaultHost = "127.0.0.1"
	// DefaultPort 是未配置 server.port 时的监听端口。
	DefaultPort = 8084
	// DefaultShutdownTimeout 是优雅退出的默认超时时间。
	DefaultShutdownTimeout = 30 * time.Second
)

默认监听参数,与 config.yml 中 server 段的缺省值保持一致。

Variables

This section is empty.

Functions

func ParseCLIFlags

func ParseCLIFlags() *config.CLIFlags

ParseCLIFlags 解析命令行参数(--config/--port/...)并登记为全局覆盖项。

命令行入口在 flag.Parse() 之后调用它;桌面入口不需要调用, 直接使用 Options.Config 或默认配置文件即可。

Types

type Options

type Options struct {
	// Config 为 nil 时按默认规则加载 config.yml(CLI --config > 环境变量 > 当前目录)。
	// 桌面端可传入预加载的配置,避免重复解析。
	Config *config.Config
	// Address 非空时直接使用该监听地址(如 "127.0.0.1:0"),
	// 否则使用 config 中的 server.host:server.port。
	Address string
	// ListenRetries / RetryDelay 控制端口占用时的重试;0 表示使用默认值。
	ListenRetries int
	RetryDelay    time.Duration
	// HandleSignals 为 true 时服务自行监听 SIGINT/SIGTERM 并优雅退出,
	// 命令行模式使用;嵌入式(桌面)模式应设为 false,由宿主控制生命周期。
	HandleSignals bool
	// InitSnowflake 为 true 时调用 utils.InitSnowflake(1)(进程内只能初始化一次)。
	// 命令行模式使用。
	InitSnowflake bool
}

Options 控制服务启动方式。

type Server

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

Server 是运行中的后端服务实例。

func New

func New(opts Options) (*Server, error)

New 加载配置并构建依赖注入容器,但暂不监听端口。

注意:依赖注入容器是包级全局(internal/runtime),一个进程只能构建一次。

func (*Server) Address

func (s *Server) Address() string

Address 返回配置中的监听地址(形如 127.0.0.1:8084)。

func (*Server) Config

func (s *Server) Config() *config.Config

Config 返回已加载的配置。

func (*Server) Done

func (s *Server) Done() <-chan struct{}

Done 返回服务正常结束(或 Shutdown 完成)时关闭的通道。

func (*Server) Err

func (s *Server) Err() <-chan error

Err 返回服务异常退出时的错误通道(带 1 个缓冲)。

func (*Server) Shutdown

func (s *Server) Shutdown(ctx context.Context) error

Shutdown 优雅关闭服务。可重复调用(幂等)。

func (*Server) Start

func (s *Server) Start() error

Start 启动 HTTP 服务并立即返回。

监听失败会直接返回错误;成功后服务在后台运行, 停止请调用 Shutdown,等待失败退出可调用 Wait。

func (*Server) Wait

func (s *Server) Wait(ctx context.Context) error

Wait 阻塞直到服务结束或 ctx 取消。 服务异常退出时返回该错误;ctx 取消时返回 ctx.Err()。

Jump to

Keyboard shortcuts

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