-
Notifications
You must be signed in to change notification settings - Fork 4
/
server_spec.go
68 lines (54 loc) · 1.82 KB
/
server_spec.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
package porthos
import "reflect"
// Spec to a remote procedure.
type Spec struct {
Description string `json:"description"`
Request ContentSpec `json:"request"`
Response ContentSpec `json:"response"`
}
// ContentSpec to a remote procedure.
type ContentSpec struct {
ContentType string `json:"contentType"`
Body interface{} `json:"body"`
}
// FieldSpec represents a spec of a body field.
type FieldSpec struct {
Type string `json:"type"`
Description string `json:"description"`
Body BodySpecMap `json:"body,omitempty"`
}
// BodySpecMap represents a body spec.
type BodySpecMap map[string]FieldSpec
// BodySpecFromStruct creates a body spec from a struct value.
// You just have to pass an "instance" of your struct.
func BodySpecFromStruct(structValue interface{}) BodySpecMap {
return bodySpecFromStructType(reflect.ValueOf(structValue).Type())
}
// BodySpecFromArray creates a body spec from a array value.
// You just have to pass an "instance" of your array.
func BodySpecFromArray(structOfTheList interface{}) []FieldSpec {
spec := make([]FieldSpec, 1)
tp := reflect.ValueOf(structOfTheList).Type()
if tp.Kind() == reflect.Struct {
child := bodySpecFromStructType(tp)
spec[0] = FieldSpec{Type: tp.Name(), Body: child}
} else {
spec[0] = FieldSpec{Type: tp.Name()}
}
return spec
}
func bodySpecFromStructType(s reflect.Type) BodySpecMap {
spec := BodySpecMap{}
for i := 0; i < s.NumField(); i++ {
f := s.Field(i)
jsonField := f.Tag.Get("json")
description := f.Tag.Get("description")
if f.Type.Kind() == reflect.Struct {
child := bodySpecFromStructType(f.Type)
spec[jsonField] = FieldSpec{Type: f.Type.Name(), Description: description, Body: child}
} else {
spec[jsonField] = FieldSpec{Type: f.Type.Name(), Description: description}
}
}
return spec
}