-
Notifications
You must be signed in to change notification settings - Fork 11
/
field.go
59 lines (50 loc) · 1.06 KB
/
field.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
package main
import (
"fmt"
"unicode"
)
// Field data type
type Field struct {
name string
gtype string
tag string
}
// Simplifies Field construction
func NewField(name, gtype string, body ...byte) Field {
if gtype == "struct" {
gtype = fmt.Sprintf("%s {%s}", gtype, body)
}
return Field{goField(name), gtype, goTag(name)}
}
// Provides Sorter interface so we can keep field order
type FieldSort []Field
func (s FieldSort) Len() int { return len(s) }
func (s FieldSort) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
func (s FieldSort) Less(i, j int) bool {
return s[i].name < s[j].name
}
// Return lower_case json fields to camel case fields.
func goField(jf string) string {
mkUpper := true
gf := ""
for _, c := range jf {
if mkUpper {
c = unicode.ToUpper(c)
mkUpper = false
}
if c == '_' {
mkUpper = true
continue
}
if c == '-' {
mkUpper = true
continue
}
gf += string(c)
}
return fmt.Sprintf("%s", gf)
}
// Returns the json tag from a json field.
func goTag(jf string) string {
return fmt.Sprintf("`json:\"%s\"`", jf)
}