-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathmatch.go
63 lines (50 loc) · 1.53 KB
/
match.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
package allot
import (
"errors"
"fmt"
"strconv"
)
// MatchInterface describes how to access a Match
type MatchInterface interface {
String(name string) (string, error)
Integer(name string) (int, error)
Match(position int) (string, error)
Parameter(param ParameterInterface) (string, error)
}
// Match is the Match definition
type Match struct {
Command CommandInterface
Request string
}
// String returns the value for a string parameter
func (m Match) String(name string) (string, error) {
return m.Parameter(NewParameterWithType(name, "string"))
}
// Integer returns the value for an integer parameter
func (m Match) Integer(name string) (int, error) {
str, err := m.Parameter(NewParameterWithType(name, "integer"))
if err != nil {
return 0, err
}
return strconv.Atoi(str)
}
// Parameter returns the value for a parameter
func (m Match) Parameter(param ParameterInterface) (string, error) {
pos := m.Command.Position(param)
if pos == -1 {
return "", errors.New("Unknonw parameter \"" + param.Name() + "\"")
}
matches := m.Command.Expression().FindAllStringSubmatch(m.Request, -1)[0][1:]
return matches[m.Command.Position(param)], nil
}
// Match returns the match at given position
func (m Match) Match(position int) (string, error) {
matches := m.Command.Expression().FindAllStringSubmatch(m.Request, -1)
if len(matches) != 1 {
return "", errors.New("Unable to parse request")
}
if position >= len(matches[0]) {
return "", fmt.Errorf("No parameter at position %d", position)
}
return matches[0][position+1], nil
}