-
Notifications
You must be signed in to change notification settings - Fork 722
/
api.go
80 lines (69 loc) · 2.17 KB
/
api.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
package api
import (
"encoding/json"
"io"
"net/http"
"github.com/julienschmidt/httprouter"
"github.com/prebid/prebid-server/stored_requests/events"
)
type eventsAPI struct {
saves chan events.Save
invalidations chan events.Invalidation
}
// NewEventsAPI creates an EventProducer that generates cache events from HTTP requests.
// The returned httprouter.Handle must be registered on both POST (update) and DELETE (invalidate)
// methods and provided an `:id` param via the URL, e.g.:
//
// apiEvents, apiEventsHandler, err := NewEventsApi()
// router.POST("/stored_requests", apiEventsHandler)
// router.DELETE("/stored_requests", apiEventsHandler)
// listener := events.Listen(cache, apiEvents)
//
// The returned HTTP endpoint should not be exposed on a public network without authentication
// as it allows direct writing to the cache via Update.
func NewEventsAPI() (events.EventProducer, httprouter.Handle) {
api := &eventsAPI{
invalidations: make(chan events.Invalidation),
saves: make(chan events.Save),
}
return api, httprouter.Handle(api.HandleEvent)
}
func (api *eventsAPI) HandleEvent(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
if r.Method == "POST" {
body, err := io.ReadAll(r.Body)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte("Missing update data.\n"))
return
}
var save events.Save
if err := json.Unmarshal(body, &save); err != nil {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte("Invalid update.\n"))
return
}
api.saves <- save
} else if r.Method == "DELETE" {
body, err := io.ReadAll(r.Body)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte("Missing invalidation data.\n"))
return
}
var invalidation events.Invalidation
if err := json.Unmarshal(body, &invalidation); err != nil {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte("Invalid invalidation.\n"))
return
}
api.invalidations <- invalidation
} else {
w.WriteHeader(http.StatusMethodNotAllowed)
}
}
func (api *eventsAPI) Invalidations() <-chan events.Invalidation {
return api.invalidations
}
func (api *eventsAPI) Saves() <-chan events.Save {
return api.saves
}