forked from miquella/caddy-awses
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdipatcher.go
50 lines (39 loc) · 1.02 KB
/
dipatcher.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
package awses
import (
"net/http"
"strings"
"github.com/caddyserver/caddy/caddyhttp/httpserver"
)
type Dispatcher struct {
Configs []*Config
Next httpserver.Handler
handlers map[*Config]*Handler
}
func NewDispatcher(configs []*Config, next httpserver.Handler) *Dispatcher {
handlers := make(map[*Config]*Handler)
for _, config := range configs {
handlers[config] = NewHandler(config)
}
return &Dispatcher{
Configs: configs,
Next: next,
handlers: handlers,
}
}
func (d Dispatcher) ConfigForRequest(r *http.Request) *Config {
for _, config := range d.Configs {
if r.URL.Path == config.Path || strings.HasPrefix(r.URL.Path, config.Path+"/") {
return config
}
}
return nil
}
func (d Dispatcher) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, error) {
config := d.ConfigForRequest(r)
if config == nil {
return d.Next.ServeHTTP(w, r)
}
// strip the prefix before dispatching the handler
r.URL.Path = strings.TrimPrefix(r.URL.Path, config.Path)
return d.handlers[config].ServeHTTP(w, r)
}