-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnesting.go
63 lines (50 loc) · 1.35 KB
/
nesting.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
// Tideland Go HTTP Extensions
//
// Copyright (C) 2020-2022 Frank Mueller / Tideland / Oldenburg / Germany
//
// All rights reserved. Use of this source code is governed
// by the new BSD license.
package httpx // import "tideland.dev/go/httpx"
//--------------------
// IMPORTS
//--------------------
import (
"net/http"
"sync"
)
//--------------------
// NESTED MULTIPLEXER
//--------------------
// NestedMux allows to nest handler following the RESTful API pattern
// {prefix}/{resource}/{id}/{subresource}/{subresource-id}/...
type NestedMux struct {
mu sync.RWMutex
prefix string
handlers map[string]http.Handler
}
// NewNestedMux creates an empty nested multiplexer.
func NewNestedMux(prefix string) *NestedMux {
return &NestedMux{
prefix: prefix,
handlers: make(map[string]http.Handler),
}
}
// Handle registers the handler for the given resource name. Nested names are separated by a slash.
func (mux *NestedMux) Handle(path string, h http.Handler) {
mux.mu.Lock()
defer mux.mu.Unlock()
mux.handlers[path] = h
}
// ServeHTTP implements http.Handler.
func (mux *NestedMux) ServeHTTP(w http.ResponseWriter, r *http.Request) {
mux.mu.RLock()
defer mux.mu.RUnlock()
ress := PathToResources(r, mux.prefix)
path := ress.Path()
h, exists := mux.handlers[path]
if !exists {
h = http.NotFoundHandler()
}
h.ServeHTTP(w, r)
}
// EOF