forked from gobuffalo/pop
-
Notifications
You must be signed in to change notification settings - Fork 0
/
string.go
74 lines (62 loc) · 1.76 KB
/
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
package slices
import (
"database/sql/driver"
"encoding/json"
"fmt"
"strings"
"github.com/pkg/errors"
)
// For reading in arrays from postgres
// String is a slice of strings.
type String []string
// Interface implements the nulls.nullable interface.
func (s String) Interface() interface{} {
return []string(s)
}
// Scan implements the sql.Scanner interface.
// It allows to read the string slice from the database value.
func (s *String) Scan(src interface{}) error {
b, ok := src.([]byte)
if !ok {
return errors.New("Scan source was not []byte")
}
(*s) = strToString(string(b))
return nil
}
// Value implements the driver.Valuer interface.
// It allows to convert the string slice to a driver.value.
func (s String) Value() (driver.Value, error) {
return fmt.Sprintf("{%s}", strings.Join(s, ",")), nil
}
// UnmarshalJSON will unmarshall JSON value into
// the string slice representation of this value.
func (s *String) UnmarshalJSON(data []byte) error {
ss := []string{}
if err := json.Unmarshal(data, &ss); err != nil {
return err
}
(*s) = String(ss)
return nil
}
// UnmarshalText will unmarshall text value into
// the string slice representation of this value.
func (s *String) UnmarshalText(text []byte) error {
ss := []string{}
for _, x := range strings.Split(string(text), ",") {
ss = append(ss, strings.TrimSpace(x))
}
(*s) = ss
return nil
}
// TagValue implements the tagValuer interface, to work with https://github.com/gobuffalo/tags.
func (s String) TagValue() string {
return s.Format(",")
}
// Format presents the slice as a string, using a given separator.
func (s String) Format(sep string) string {
return strings.Join([]string(s), sep)
}
func strToString(s string) []string {
r := strings.Trim(s, "{}")
return strings.Split(r, ",")
}