-
Notifications
You must be signed in to change notification settings - Fork 0
/
doc_test.go
109 lines (90 loc) · 2.26 KB
/
doc_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
package coda_test
import (
"context"
"database/sql"
"errors"
"log"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"github.com/marnixbouhuis/coda"
)
func Example() {
sd := coda.NewShutdown(
coda.WithShutdownLogger(coda.NewStdLogger(log.Default())),
)
// Create groups with dependencies
dbGroup := coda.Must(sd.NewGroup("database", nil,
coda.WithGroupShutdownTimeout(5*time.Second),
))
workerGroup := coda.Must(sd.NewGroup("workers", []*coda.Group{dbGroup},
coda.WithGroupShutdownTimeout(10*time.Second),
))
// Database connection
dbGroup.Go(func(ctx context.Context, ready func()) error {
db, err := sql.Open("postgres", "connection-string")
if err != nil {
return err
}
defer db.Close()
ready()
<-ctx.Done()
return nil
}, coda.WithBlock(true))
// Start multiple workers
for workerID := range 3 {
workerGroup.Go(func(ctx context.Context, ready func()) error {
log.Printf("Worker %d starting", workerID)
ready()
for {
select {
case <-ctx.Done():
log.Printf("Worker %d shutting down", workerID)
return nil
case <-time.After(time.Second):
// Do some work
log.Printf("Worker %d processing", workerID)
}
}
}, coda.WithBlock(true))
}
serverGroup := coda.Must(sd.NewGroup("server", []*coda.Group{workerGroup, dbGroup}))
serverGroup.Go(func(ctx context.Context, ready func()) error {
ready()
mux := http.NewServeMux()
srv := &http.Server{
Addr: ":8080",
Handler: mux,
ReadTimeout: 5 * time.Second,
WriteTimeout: 10 * time.Second,
}
mux.HandleFunc("/demo", func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusOK)
})
go func() {
<-ctx.Done()
shutdownCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), time.Second*30)
defer cancel()
if err := srv.Shutdown(shutdownCtx); err != nil {
log.Printf("Failed to stop HTTP server gracefully: %v", err)
sd.StopWithError(err)
}
}()
if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
return err
}
return nil
})
go func() {
ch := make(chan os.Signal, 1)
signal.Notify(ch, syscall.SIGINT, syscall.SIGTERM)
<-ch
sd.Stop()
}()
if err := sd.Wait(); err != nil {
log.Printf("Shutdown error: %v", err)
os.Exit(1)
}
}