-
Notifications
You must be signed in to change notification settings - Fork 23
/
signaling.go
52 lines (44 loc) · 1.44 KB
/
signaling.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
package internal
import (
"context"
"net/http"
"sync/atomic"
"github.com/poki/netlib/internal/cloudflare"
"github.com/poki/netlib/internal/signaling"
"github.com/poki/netlib/internal/signaling/stores"
"github.com/poki/netlib/internal/util"
)
func Signaling(ctx context.Context, store stores.Store, credentialsClient *cloudflare.CredentialsClient) (http.Handler, func()) {
mux := http.NewServeMux()
openConnections, signaling := signaling.Handler(ctx, store, credentialsClient)
cleanup := func() {
openConnections.Wait()
}
mux.Handle("/v0/signaling", signaling)
hasCredentials := uint32(0)
mux.HandleFunc("/ready", func(w http.ResponseWriter, r *http.Request) {
if atomic.LoadUint32(&hasCredentials) != 0 {
w.WriteHeader(http.StatusOK)
return
}
creds, _ := credentialsClient.GetCredentials(r.Context())
if creds != nil {
atomic.StoreUint32(&hasCredentials, 1)
w.WriteHeader(http.StatusOK)
return
}
w.WriteHeader(http.StatusServiceUnavailable)
})
healthCheck := func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" && r.URL.Path != "/health" {
util.ErrorAndAbort(w, r, http.StatusNotFound, "not-found")
}
w.Header().Set("Content-Type", "application/json")
w.Header().Set("X-Content-Type-Options", "nosniff")
w.WriteHeader(http.StatusOK)
w.Write([]byte("{\"healthy\":true}\n")) //nolint:errcheck
}
mux.HandleFunc("/health", healthCheck)
mux.HandleFunc("/", healthCheck)
return mux, cleanup
}