Skip to content

Commit 60a5b41

Browse files
committed
refactor(canal): error handling on startup
1 parent 1a67e77 commit 60a5b41

File tree

2 files changed

+27
-13
lines changed

2 files changed

+27
-13
lines changed

canal/canal.go

+26-12
Original file line numberDiff line numberDiff line change
@@ -18,11 +18,15 @@ import (
1818
"context"
1919
"fmt"
2020
"net/http"
21+
"os"
22+
"os/signal"
23+
"syscall"
2124
"time"
2225

2326
"github.com/prometheus/client_golang/prometheus/promhttp"
2427
"github.com/trim21/errgo"
2528
"go.uber.org/fx"
29+
"golang.org/x/sync/errgroup"
2630

2731
"github.com/bangumi/server/config"
2832
"github.com/bangumi/server/dal"
@@ -82,23 +86,33 @@ func Main() error {
8286
return errgo.Wrap(err, "fx")
8387
}
8488

85-
var errChan = make(chan error, 1)
86-
8789
// metrics http reporter
8890
mux := http.NewServeMux()
8991
mux.Handle("/metrics", promhttp.Handler())
9092
srv := &http.Server{Addr: h.config.ListenAddr(), Handler: mux, ReadHeaderTimeout: time.Second}
91-
go func() { errChan <- errgo.Wrap(srv.ListenAndServe(), "http") }()
93+
94+
var wg errgroup.Group
95+
9296
defer srv.Shutdown(context.Background()) //nolint:errcheck
97+
wg.Go(func() error {
98+
return errgo.Wrap(srv.ListenAndServe(), "http")
99+
})
93100

94-
go func() { errChan <- errgo.Wrap(h.start(), "start") }()
95101
defer h.Close()
96-
97-
select {
98-
case err := <-errChan:
99-
return err
100-
case <-sys.HandleSignal():
101-
logger.Info("receive signal, shutdown")
102-
return nil
103-
}
102+
wg.Go(func() error {
103+
return errgo.Wrap(h.start(), "start")
104+
})
105+
106+
wg.Go(func() error {
107+
sigChan := make(chan os.Signal, 1)
108+
signal.Notify(sigChan, os.Interrupt, syscall.SIGTERM)
109+
110+
select {
111+
case <-sys.HandleSignal():
112+
logger.Info("receive signal, shutdown")
113+
return fmt.Errorf("receive signal")
114+
}
115+
})
116+
117+
wg.Wait()
104118
}

go.mod

+1-1
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@ require (
3838
github.com/trim21/pkg v0.0.4
3939
go.uber.org/fx v1.23.0
4040
go.uber.org/zap v1.27.0
41+
golang.org/x/sync v0.12.0
4142
golang.org/x/text v0.23.0
4243
gopkg.in/yaml.v3 v3.0.1
4344
gorm.io/driver/mysql v1.5.7
@@ -114,7 +115,6 @@ require (
114115
golang.org/x/exp v0.0.0-20250210185358-939b2ce775ac // indirect
115116
golang.org/x/mod v0.23.0 // indirect
116117
golang.org/x/net v0.36.0 // indirect
117-
golang.org/x/sync v0.12.0 // indirect
118118
golang.org/x/sys v0.31.0 // indirect
119119
golang.org/x/term v0.30.0 // indirect
120120
golang.org/x/time v0.8.0 // indirect

0 commit comments

Comments
 (0)