/
common.go
66 lines (56 loc) · 1.47 KB
/
common.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
package swagger
import (
"encoding/json"
"fmt"
"reflect"
"runtime"
"strings"
)
type Common struct {
errors []error
data map[string]reflect.Value
}
func NewCommon() *Common {
return &Common{data: make(map[string]reflect.Value, 0), errors: make([]error, 0)}
}
func (s *Common) HasErrors() bool {
return len(s.errors) > 0
}
func (s *Common) Error() string {
var errors []string
for _, err := range s.errors {
errors = append(errors, err.Error())
}
return strings.Join(errors, "\n")
}
func (p *Common) Set(name interface{}, object interface{}) {
p.data[fmt.Sprintf("%v", name)] = reflect.ValueOf(object)
}
func (s *Common) ExtendSlice(i interface{}, with interface{}) {
name := fmt.Sprintf("%v", i)
m, ok := s.data[name]
if !ok {
m = reflect.MakeSlice(reflect.SliceOf(reflect.TypeOf(with)), 0, 0)
}
s.data[name] = reflect.Append(m, reflect.ValueOf(with))
}
func (s *Common) ExtendMap(i interface{}, with interface{}) {
name := fmt.Sprintf("%v", i)
m, ok := s.data[name]
if !ok {
m = reflect.MakeMap(reflect.MapOf(reflect.TypeOf(""), reflect.TypeOf(with)))
}
m.SetMapIndex(reflect.ValueOf(name), reflect.ValueOf(with))
s.data[name] = m
}
func (s *Common) AddError(err error) {
_, fn, line, _ := runtime.Caller(1)
s.errors = append(s.errors, fmt.Errorf("[error] %s:%d %v", fn, line, err))
}
func (s *Common) MarshalJSON() ([]byte, error) {
data := make(map[string]interface{}, 0)
for k, v := range s.data {
data[k] = v.Interface()
}
return json.Marshal(data)
}