-
Notifications
You must be signed in to change notification settings - Fork 1
/
route.go
64 lines (53 loc) · 1.19 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
package docs
import (
"bytes"
"html"
"reflect"
"regexp"
"strings"
"github.com/lovego/struct_tag"
)
type Route struct {
req, resp reflect.Type
}
func (r *Route) Parse(handler interface{}) bool {
typ := reflect.TypeOf(handler)
if typ.NumIn() != 2 {
return false
}
r.req, r.resp = typ.In(0), typ.In(1).Elem()
return true
}
func (r *Route) Doc(method, fullPath string) []byte {
buf := bytes.NewBufferString(
"# " + r.Title() + "<br>" + r.MethodPath(method, fullPath) + "\n",
)
r.Desc(buf)
r.Param(buf, fullPath)
r.Query(buf)
r.Header(buf)
r.Body(buf)
r.RespHeader(buf)
r.RespBody(buf)
r.RespError(buf)
return buf.Bytes()
}
func (r *Route) MethodPath(method, fullPath string) string {
return method + " " + html.EscapeString(fullPath)
}
var whitespaceRegexp = regexp.MustCompile(`\s+`)
// extract comment from struct field tags
func getComment(tag reflect.StructTag) string {
tagStr := string(tag)
comment, _ := struct_tag.Lookup(tagStr, `comment`)
if comment == `` {
comment, _ = struct_tag.Lookup(tagStr, `c`)
}
if comment != `` {
comment = strings.TrimSpace(comment)
}
if comment != `` {
comment = whitespaceRegexp.ReplaceAllString(comment, " ")
}
return comment
}