-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmux.go
75 lines (61 loc) · 1.82 KB
/
mux.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
package epplib
import (
"context"
"io"
"github.com/beevik/etree"
)
// CommandMux parses and routes xml commands to bound handlers.
type CommandMux struct {
greetingCommand CommandFunc
handlers []handler
Logger Logger
}
// GetGreeting returns a greeting.
func (c *CommandMux) GetGreeting(ctx context.Context, rw *ResponseWriter) {
c.greetingCommand(ctx, rw, nil)
}
// Handle handles a command. Commands will be routed according to how they are
// bound by the Bind function.
func (c *CommandMux) Handle(ctx context.Context, rw *ResponseWriter, cmd io.Reader) {
doc := etree.NewDocument()
_, err := doc.ReadFrom(cmd)
if err != nil {
c.Logger.Infof("could not read command, err: %s", err)
rw.CloseAfterWrite()
return
}
for _, h := range c.handlers {
if el := doc.FindElementPath(h.path); el != nil {
h.fn(ctx, rw, doc)
return
}
}
c.Logger.Infof("unknown command")
rw.CloseAfterWrite()
}
// BindGreeting bind a greeting handler. Useful because EPP needs to send a
// greeting on connect.
func (c *CommandMux) BindGreeting(handler CommandFunc) {
c.greetingCommand = handler
}
// Bind will bind a handler to a path.
func (c *CommandMux) Bind(path string, handlerFunc CommandFunc) {
if c.handlers == nil {
c.handlers = make([]handler, 0, 1)
}
c.handlers = append(c.handlers, handler{
fn: handlerFunc,
path: etree.MustCompilePath(path),
})
}
// BindCommand is a convenience method wrapping `Bind` with the common pattern used in
// epp. Note that it's currently hardcoded in the namespace-uri versions since there is
// currently only one.
func (c *CommandMux) BindCommand(command, ns string, handlerFunc CommandFunc) {
c.Bind(NewXMLPathBuilder().
AddOrphan("//command", "urn:ietf:params:xml:ns:epp-1.0").
Add(command, "urn:ietf:params:xml:ns:epp-1.0").
Add(command, ns).String(),
handlerFunc,
)
}