-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathroute.go
130 lines (119 loc) · 2.53 KB
/
route.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
package main
import (
"bytes"
"errors"
"fmt"
"io"
"strings"
)
type Route struct {
routeParams []*RouteParam
}
type RouteParam struct {
nameAddr *NameAddr
rrParam []KeyValue
}
func NewRouteParam() *RouteParam {
return &RouteParam{nameAddr: nil, rrParam: make([]KeyValue, 0)}
}
func (rp *RouteParam) GetAddress() *NameAddr {
return rp.nameAddr
}
func ParseRoute(s string) (*Route, error) {
route := &Route{}
for _, routeParam := range strings.Split(s, ",") {
param, err := parseRouteParam(routeParam)
if err != nil {
return nil, err
}
route.routeParams = append(route.routeParams, param)
}
return route, nil
}
func parseRouteParam(s string) (*RouteParam, error) {
r := NewRouteParam()
pos := strings.Index(s, ">")
if pos == -1 {
return nil, errors.New("route-param syntax error")
}
nameAddr, err := ParseNameAddr(s[0 : pos+1])
if err != nil {
return nil, err
}
r.nameAddr = nameAddr
s = strings.TrimSpace(s[pos+1:])
if len(s) <= 0 {
return r, nil
}
if s[0] != ';' {
return nil, errors.New("route-param syntax error")
}
s = s[1:]
for _, t := range strings.Split(s, ";") {
param, err := ParseGenericParam(t)
if err != nil {
return nil, err
}
r.rrParam = append(r.rrParam, param)
}
return r, nil
}
func (r *Route) GetRouteParam(index int) (*RouteParam, error) {
if index < 0 || index >= len(r.routeParams) {
return nil, fmt.Errorf("index %d is out of bound", index)
}
return r.routeParams[index], nil
}
func (r *Route) PopRouteParam() (*RouteParam, error) {
if len(r.routeParams) > 0 {
routeParam := r.routeParams[0]
r.routeParams = r.routeParams[1:]
return routeParam, nil
}
return nil, errors.New("no route-param")
}
func (r *Route) GetRouteParamCount() int {
return len(r.routeParams)
}
func (r *Route) Write(writer io.Writer) (int, error) {
n := 0
for index, param := range r.routeParams {
if index != 0 {
m, err := fmt.Fprintf(writer, ",")
n += m
if err != nil {
return n, err
}
}
m, err := param.Write(writer)
n += m
if err != nil {
return n, err
}
}
return n, nil
}
func (r *Route) String() string {
buf := bytes.NewBuffer(make([]byte, 0))
r.Write(buf)
return buf.String()
}
func (r *RouteParam) Write(writer io.Writer) (int, error) {
n, err := r.nameAddr.Write(writer)
if err != nil {
return n, err
}
for _, param := range r.rrParam {
m, err := param.Write(writer)
n += m
if err != nil {
return n, err
}
}
return n, nil
}
func (r *RouteParam) String() string {
buf := bytes.NewBuffer(make([]byte, 0))
r.Write(buf)
return buf.String()
}