upp/run.go

103 lines
1.7 KiB
Go
Raw Normal View History

2025-01-01 21:01:05 -08:00
package upp
import (
"context"
2025-01-02 22:44:20 +08:00
"fmt"
2025-01-01 21:01:05 -08:00
"os/signal"
"syscall"
"github.com/loveuer/upp/pkg/interfaces"
"github.com/loveuer/upp/pkg/tool"
)
2025-01-02 22:44:20 +08:00
func (u *upp) startAPI(ctx context.Context) {
2025-01-01 22:14:45 -08:00
address := env.ListenHttp
2025-01-01 21:01:05 -08:00
if address == "" {
address = u.api.config.Address
}
2025-01-02 22:44:20 +08:00
fmt.Printf("Upp | api listen at %s\n", address)
2025-01-01 21:01:05 -08:00
go u.api.engine.Run(address)
go func() {
<-ctx.Done()
u.api.engine.Shutdown(tool.Timeout(2))
}()
}
2025-01-02 22:44:20 +08:00
func (u *upp) startTask(ctx context.Context) {
fmt.Printf("Upp | start task channel[%02d]", len(u.taskCh))
2025-01-01 21:01:05 -08:00
for _, _ch := range u.taskCh {
go func(ch <-chan func(interfaces.Upp) error) {
var err error
for {
select {
case <-ctx.Done():
case task, ok := <-ch:
if !ok {
return
}
if err = task(u); err != nil {
u.UseLogger(ctx).Error(err.Error())
}
}
}
}(_ch)
}
}
func (u *upp) Run(ctx context.Context) {
u.RunSignal(ctx)
}
2025-01-02 22:44:20 +08:00
func (u *upp) runInitFns(ctx context.Context) {
for _, fn := range u.initFns._sync {
2025-01-01 21:01:05 -08:00
fn(u)
}
}
2025-01-02 22:44:20 +08:00
func (u *upp) startInitFns(ctx context.Context) {
for _, fn := range u.initFns._async {
go fn(u)
}
}
2025-01-01 21:01:05 -08:00
func (u *upp) RunSignal(ctxs ...context.Context) {
c := context.Background()
if len(ctxs) > 0 {
c = ctxs[0]
}
ctx, cancel := signal.NotifyContext(c, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT)
defer cancel()
u.ctx = ctx
2025-01-02 22:44:20 +08:00
print(Banner)
if len(u.initFns._sync) > 0 {
u.runInitFns(ctx)
}
if len(u.initFns._async) > 0 {
u.startInitFns(ctx)
2025-01-01 21:01:05 -08:00
}
if u.api != nil {
2025-01-02 22:44:20 +08:00
u.startAPI(ctx)
2025-01-01 21:01:05 -08:00
}
if len(u.taskCh) > 0 {
2025-01-02 22:44:20 +08:00
u.startTask(ctx)
2025-01-01 21:01:05 -08:00
}
<-ctx.Done()
2025-01-02 22:44:20 +08:00
u.UseLogger().Warn(" Upp | quit by signal...")
2025-01-01 21:01:05 -08:00
if u.cache != nil {
u.cache.Close()
}
<-tool.Timeout(2).Done()
}