forked from kdar/factorcfg
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrender.go
106 lines (90 loc) · 1.91 KB
/
render.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
package factorcfg
import (
"bytes"
"errors"
"fmt"
"reflect"
"strconv"
"text/template"
)
func Render(spec interface{}, tmpl *template.Template) ([]byte, error) {
s := reflect.ValueOf(spec)
if s.Kind() != reflect.Ptr {
return nil, errors.New("spec must be a pointer to a struct")
}
s = s.Elem()
if s.Kind() != reflect.Struct {
return nil, ErrInvalidSpecification
}
fields := getTemplateFields(nil, s)
buf := &bytes.Buffer{}
err := tmpl.Execute(buf, fields)
return buf.Bytes(), err
}
func getTemplateFields(keys []string, s reflect.Value) []TemplateField {
var fields []TemplateField
typeOfSpec := s.Type()
for i := 0; i < s.NumField(); i++ {
f := s.Field(i)
t := typeOfSpec.Field(i)
if f.CanSet() {
fieldName := typeOfSpec.Field(i).Name
if f.Kind() == reflect.Struct {
keys = append(keys, fieldName)
fields = append(fields, getTemplateFields(keys, f)...)
continue
}
fields = append(fields, TemplateField{
Name: fieldName,
Value: f.Interface(),
String: fmt.Sprintf("%#v", f.Interface()),
Type: t.Type,
Tags: getTags(t.Tag),
})
}
}
return fields
}
func getTags(tag reflect.StructTag) (m map[string]string) {
for tag != "" {
if m == nil {
m = make(map[string]string)
}
// skip leading space
i := 0
for i < len(tag) && tag[i] == ' ' {
i++
}
tag = tag[i:]
if tag == "" {
break
}
// scan to colon.
// a space or a quote is a syntax error
i = 0
for i < len(tag) && tag[i] != ' ' && tag[i] != ':' && tag[i] != '"' {
i++
}
if i+1 >= len(tag) || tag[i] != ':' || tag[i+1] != '"' {
break
}
name := string(tag[:i])
tag = tag[i+1:]
// scan quoted string to find value
i = 1
for i < len(tag) && tag[i] != '"' {
if tag[i] == '\\' {
i++
}
i++
}
if i >= len(tag) {
break
}
qvalue := string(tag[:i+1])
tag = tag[i+1:]
value, _ := strconv.Unquote(qvalue)
m[name] = value
}
return
}