go项目脚手架
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

90 lines
1.6 KiB

package runtime
import (
"context"
"errors"
"os"
"os/signal"
"sorbet/pkg/log"
"syscall"
)
// Init 初始化
func Init() error {
return InitWith(context.Background())
}
func InitWith(root context.Context) error {
if ctx != nil || cancel != nil {
return errors.New("not stopped")
}
// 初始化上下文相关
ctx, cancel = context.WithCancel(root)
// 初始化退出通道
if exit == nil {
exit = make(chan chan error)
}
// 初始化信号量
if semaphore == nil {
semaphore = make(chan struct{}, 256)
}
// 初始化任务通道
if tasks != nil {
tasks = make(chan func(context.Context), 256)
}
// 初始化网络服务组件
for _, servlet := range servlets {
if err := servlet.Init(ctx); err != nil {
return err
}
}
return nil
}
func Start() error {
// 创建服务器
srv, ln, err := createServer()
if err != nil {
return err
}
// 启动网络服务器
go func() {
err := srv.Serve(ln)
if err != nil {
log.Error("encountered an error while serving listener: ", err)
}
}()
log.Info("Listening on %s", ln.Addr().String())
// 监听停止命令,停止网络服务
go func() {
errChan := <-exit
tryCancel()
errChan <- ln.Close() // stop the listener
}()
return nil
}
func Run() error {
if err := Start(); err != nil {
return err
}
// parse address for host, port
ch := make(chan os.Signal, 1)
signal.Notify(ch, syscall.SIGTERM, syscall.SIGINT)
log.Info("Received signal %s", <-ch)
return Stop()
}
// Stop 停止运行
func Stop() error {
if ctx == nil {
return errors.New("already stopped")
}
ch := make(chan error)
exit <- ch
wg.Wait()
return <-ch
}