forked from lestrrat-go/httprc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
httprc_example_test.go
81 lines (63 loc) · 1.47 KB
/
httprc_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
78
79
80
81
package httprc_test
import (
"context"
"fmt"
"net/http"
"net/http/httptest"
"sync"
"time"
"github.com/lestrrat-go/httprc"
)
const (
helloWorld = `Hello World!`
goodbyeWorld = `Goodbye World!`
)
func ExampleCache() {
var mu sync.RWMutex
msg := helloWorld
srv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set(`Cache-Control`, fmt.Sprintf(`max-age=%d`, 2))
w.WriteHeader(http.StatusOK)
mu.RLock()
fmt.Fprint(w, msg)
mu.RUnlock()
}))
defer srv.Close()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
errSink := httprc.ErrSinkFunc(func(err error) {
fmt.Printf("%s\n", err)
})
c := httprc.NewCache(ctx,
httprc.WithErrSink(errSink),
httprc.WithRefreshWindow(time.Second), // force checks every second
)
c.Register(srv.URL,
httprc.WithHTTPClient(srv.Client()), // we need client with TLS settings
httprc.WithMinRefreshInterval(time.Second), // allow max-age=1 (smallest)
)
payload, err := c.Get(ctx, srv.URL)
if err != nil {
fmt.Printf("%s\n", err)
return
}
if string(payload.([]byte)) != helloWorld {
fmt.Printf("payload mismatch: %s\n", payload)
return
}
mu.Lock()
msg = goodbyeWorld
mu.Unlock()
time.Sleep(4 * time.Second)
payload, err = c.Get(ctx, srv.URL)
if err != nil {
fmt.Printf("%s\n", err)
return
}
if string(payload.([]byte)) != goodbyeWorld {
fmt.Printf("payload mismatch: %s\n", payload)
return
}
cancel()
// OUTPUT:
}