-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver.go
89 lines (65 loc) · 1.42 KB
/
server.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
package goherence
import (
"context"
"fmt"
"net/http"
"strings"
"sync"
"time"
"go.cryptoscope.co/luigi"
)
type Server interface {
RegisterPartial(Partial) func()
http.Handler
}
func NewServer() Server {
var (
mux = http.NewServeMux()
s = &server{
start: time.Now(),
partials: map[string]Partial{},
httpMux: mux,
c: newCacher(),
l: &sync.Mutex{},
}
)
mux.Handle("/coherence/cache", s.c)
mux.HandleFunc("/partial/", s.servePartialHTTP)
return s
}
type server struct {
l sync.Locker
start time.Time
partials map[string]Partial
httpMux *http.ServeMux
c *cacher
}
func (s *server) RegisterPartial(p Partial) func() {
s.l.Lock()
defer s.l.Unlock()
s.partials[p.ID()] = p
unreg := p.Register(luigi.FuncSink(func(ctx context.Context, v interface{}, err error) error {
fmt.Printf("invalidate sink for %s called with value %v and error %v\n",
p.ID(), v, err)
if err != nil {
return nil
}
return s.c.Invalidate(ctx, p.InvalidateID())
}))
return unreg
}
func (s *server) servePartialHTTP(w http.ResponseWriter, r *http.Request) {
s.l.Lock()
defer s.l.Unlock()
id := strings.TrimPrefix(r.URL.Path, "/partial/")
p, ok := s.partials[id]
if !ok {
http.Error(w, "Not Found", 404)
return
}
p.ServeHTTP(w, r)
}
func (s *server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Connection", "keep-alive")
s.httpMux.ServeHTTP(w, r)
}