-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathhttp-handler.go
62 lines (54 loc) · 1.6 KB
/
http-handler.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
package bifrost_http
import (
"context"
"net/http"
"github.com/aperturerobotics/util/ccontainer"
"github.com/aperturerobotics/util/refcount"
)
// HTTPHandler implements a HTTP handler which deduplicates with a reference count.
type HTTPHandler struct {
// handleCtr is the refcount handle to the UnixFS
handleCtr *ccontainer.CContainer[http.Handler]
// errCtr contains any error building FSHandle
errCtr *ccontainer.CContainer[*error]
// rc is the refcount container
rc *refcount.RefCount[http.Handler]
}
// NewHTTPHandler constructs a new HTTPHandler.
//
// NOTE: if ctx == nil the handler won't work until SetContext is called.
func NewHTTPHandler(
ctx context.Context,
builder HTTPHandlerBuilder,
) *HTTPHandler {
h := &HTTPHandler{
handleCtr: ccontainer.NewCContainer[http.Handler](nil),
errCtr: ccontainer.NewCContainer[*error](nil),
}
h.rc = refcount.NewRefCount(ctx, false, h.handleCtr, h.errCtr, builder)
return h
}
// SetContext sets the context for the HTTPHandler.
func (h *HTTPHandler) SetContext(ctx context.Context) {
h.rc.SetContext(ctx)
}
// ServeHTTP serves a http request.
func (h *HTTPHandler) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
ctx := req.Context()
err := h.rc.Access(ctx, true, func(ctx context.Context, access http.Handler) error {
if access == nil {
rw.WriteHeader(404)
_, _ = rw.Write([]byte("404 not found"))
return nil
}
access.ServeHTTP(rw, req.WithContext(ctx))
return nil
})
if err != nil {
rw.WriteHeader(500)
_, _ = rw.Write([]byte(err.Error()))
return
}
}
// _ is a type assertion
var _ http.Handler = ((*HTTPHandler)(nil))