-
Notifications
You must be signed in to change notification settings - Fork 1
/
example_test.go
71 lines (57 loc) · 1.24 KB
/
example_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
package svc_test
import (
"context"
"fmt"
"net/http"
"time"
"github.com/remind101/pkg/httpx"
"github.com/remind101/pkg/svc"
)
func Example() {
env := svc.InitAll()
defer env.Close()
r := httpx.NewRouter()
r.Handle("/hello", httpx.HandlerFunc(func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
fmt.Fprintln(w, "Hello world!")
return nil
}))
h := svc.NewStandardHandler(svc.HandlerOpts{
Router: r,
Reporter: env.Reporter,
HandlerTimeout: 15 * time.Second,
})
s := svc.NewServer(h, svc.WithPort("8080"))
// To illustrate shutting down a background process when server shuts down.
bg := NewBGProc()
bg.Start()
svc.RunServer(s, bg.Stop)
}
type BackgroundProcess struct {
shutdown chan struct{}
done chan struct{}
}
func NewBGProc() *BackgroundProcess {
return &BackgroundProcess{
shutdown: make(chan struct{}),
done: make(chan struct{}),
}
}
func (p *BackgroundProcess) Start() {
go p.start()
}
func (p *BackgroundProcess) start() {
defer close(p.done)
t := time.NewTicker(1 * time.Second)
for {
select {
case <-t.C:
fmt.Println("tick")
case <-p.shutdown:
return
}
}
}
func (p *BackgroundProcess) Stop() {
close(p.shutdown)
<-p.done // Wait for p to finish.
}