-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparse.route.go
76 lines (68 loc) · 1.27 KB
/
parse.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
package nji
import (
"fmt"
"reflect"
"strings"
)
type methodI interface {
Method() string
}
type routeI interface {
methodI
Path() string
}
type Route[M methodI, R routeI] struct {
_ R
m M
}
func tname(s string) string {
return strings.Split(s, "[")[0]
}
func (r Route[M, R]) Path() string {
return ParseURL[R]()
}
func (r Route[M, R]) Method() string {
return r.m.Method()
}
func ParseURL[R routeI]() string {
rr := *new(R)
t := reflect.TypeOf(rr)
path := ""
params := []string{}
if t.Kind() == reflect.Struct {
length := t.NumField()
for i := 0; i < length; i++ {
f := t.Field(i)
if tname(f.Type.String()) == "plugins.PathParam" {
params = append(params, f.Name)
}
v := reflect.New(f.Type).Interface()
if fv, ok := v.(routeI); ok {
if path != "" {
panic("couldnt use `Route` more than one in `View` struct")
}
path = fv.Path()
if string(f.Tag) == "" {
path += "/" + t.Name()
} else {
path += "/" + string(f.Tag)
}
}
}
} else {
panic("Route")
}
for _, p := range params {
path += `/:` + p
}
return path
}
func Register[R routeI, P interface {
Handle(*Context)
*R
}](eg *Engine) {
url := ParseURL[R]()
fmt.Println(url)
method := (*new(R)).Method()
eg.Handle(method, url, MakeHandle[R, P]())
}