-
-
Notifications
You must be signed in to change notification settings - Fork 59
/
hexcolor.go
87 lines (72 loc) · 1.72 KB
/
hexcolor.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
package colorful
import (
"database/sql/driver"
"encoding/json"
"fmt"
"reflect"
)
// A HexColor is a Color stored as a hex string "#rrggbb". It implements the
// database/sql.Scanner, database/sql/driver.Value,
// encoding/json.Unmarshaler and encoding/json.Marshaler interfaces.
type HexColor Color
type errUnsupportedType struct {
got interface{}
want reflect.Type
}
func (hc *HexColor) Scan(value interface{}) error {
s, ok := value.(string)
if !ok {
return errUnsupportedType{got: reflect.TypeOf(value), want: reflect.TypeOf("")}
}
c, err := Hex(s)
if err != nil {
return err
}
*hc = HexColor(c)
return nil
}
func (hc *HexColor) Value() (driver.Value, error) {
return Color(*hc).Hex(), nil
}
func (e errUnsupportedType) Error() string {
return fmt.Sprintf("unsupported type: got %v, want a %s", e.got, e.want)
}
func (hc *HexColor) UnmarshalJSON(data []byte) error {
var hexCode string
if err := json.Unmarshal(data, &hexCode); err != nil {
return err
}
var col, err = Hex(hexCode)
if err != nil {
return err
}
*hc = HexColor(col)
return nil
}
func (hc HexColor) MarshalJSON() ([]byte, error) {
return json.Marshal(Color(hc).Hex())
}
// Decode - deserialize function for https://github.com/kelseyhightower/envconfig
func (hc *HexColor) Decode(hexCode string) error {
var col, err = Hex(hexCode)
if err != nil {
return err
}
*hc = HexColor(col)
return nil
}
func (hc HexColor) MarshalYAML() (interface{}, error) {
return Color(hc).Hex(), nil
}
func (hc *HexColor) UnmarshalYAML(unmarshal func(interface{}) error) error {
var hexCode string
if err := unmarshal(&hexCode); err != nil {
return err
}
var col, err = Hex(hexCode)
if err != nil {
return err
}
*hc = HexColor(col)
return nil
}