-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsliced_string.go
96 lines (83 loc) · 2.04 KB
/
sliced_string.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
package extratypes
import (
"encoding/json"
"fmt"
"reflect"
)
// SlicedString parses and translate either a string or a slice of strings
// based on serialization JSON/Text/DB.
type SlicedString []string
// UnmarshalJSON for contacts
func (s *SlicedString) UnmarshalJSON(data []byte) error {
var str interface{}
err := json.Unmarshal(data, &str)
if err != nil {
return err
}
items := reflect.ValueOf(str)
kind := items.Kind()
var result SlicedString
switch kind {
case reflect.String:
result = append(result, items.String())
case reflect.Slice:
for i := 0; i < items.Len(); i++ {
item := items.Index(i)
switch item.Kind() {
case reflect.String:
result = append(result, item.String())
case reflect.Interface:
sliceItem := reflect.ValueOf(item.Interface())
sliceKind := sliceItem.Kind()
switch sliceKind {
case reflect.String:
result = append(result, sliceItem.String())
default:
return fmt.Errorf("unsupported type '%s' in slice", sliceKind)
}
}
}
default:
return fmt.Errorf("unsupported type '%s'", kind)
}
*s = make(SlicedString, 0, len(result))
*s = result
return nil
}
// Scan implements the Scanner interface.
func (s *SlicedString) Scan(value interface{}) error {
if value == nil {
s = nil
return nil
}
items := reflect.ValueOf(value)
kind := items.Kind()
var result SlicedString
switch kind {
case reflect.String:
result = append(result, items.String())
case reflect.Slice:
for i := 0; i < items.Len(); i++ {
item := items.Index(i)
switch item.Kind() {
case reflect.String:
result = append(result, item.String())
case reflect.Interface:
sliceItem := reflect.ValueOf(item.Interface())
sliceKind := sliceItem.Kind()
switch sliceKind {
case reflect.String:
result = append(result, sliceItem.String())
default:
return fmt.Errorf("unsupported type '%s' in slice", sliceKind)
}
}
}
default:
return fmt.Errorf("unsupported type '%s'", kind)
}
*s = make(SlicedString, 0, len(result))
*s = result
return nil
return nil
}