-
Notifications
You must be signed in to change notification settings - Fork 0
/
example_test.go
77 lines (61 loc) · 1.34 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
72
73
74
75
76
77
package concwg_test
import (
"errors"
"fmt"
"log"
"net/http"
"net/http/httptest"
"time"
"github.com/m-zajac/concwg"
)
type myWorker struct {
wg *concwg.WaitGroup
}
func newWorker() *myWorker {
return &myWorker{
wg: concwg.New(),
}
}
func (s *myWorker) HandleTask(name string) error {
if ok := s.wg.Add(1); !ok {
return errors.New("server is closing")
}
defer s.wg.Done()
// Simulate doing some work.
time.Sleep(time.Second)
fmt.Printf("task '%s' done", name)
return nil
}
func (s *myWorker) Stop() {
s.wg.Wait()
}
// This example shows the simple use case of the concwg.WaitGroup
func ExampleWaitGroup() {
worker := newWorker()
handler := func(w http.ResponseWriter, r *http.Request) {
err := worker.HandleTask(r.URL.Path)
if err != nil {
log.Printf("calling worer: %v", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusAccepted)
}
// Start a server.
srv := httptest.NewServer(http.HandlerFunc(handler))
// Handle a request.
resp, err := http.DefaultClient.Get(srv.URL + "/foo")
if err != nil {
panic(err)
}
if resp.StatusCode != http.StatusAccepted {
panic("unexpected status code")
}
// Close the server
srv.Close()
// Stop the worker, wait for all tasks to be finished.
worker.Stop()
// You can safely exit the program now.
// Output:
// task '/foo' done
}