| 1 |
package colorful |
| 2 |
|
| 3 |
import ( |
| 4 |
"database/sql/driver" |
| 5 |
"encoding/json" |
| 6 |
"fmt" |
| 7 |
"reflect" |
| 8 |
) |
| 9 |
|
| 10 |
// A HexColor is a Color stored as a hex string "#rrggbb". It implements the |
| 11 |
// database/sql.Scanner, database/sql/driver.Value, |
| 12 |
// encoding/json.Unmarshaler and encoding/json.Marshaler interfaces. |
| 13 |
type HexColor Color |
| 14 |
|
| 15 |
type errUnsupportedType struct { |
| 16 |
got interface{} |
| 17 |
want reflect.Type |
| 18 |
} |
| 19 |
|
| 20 |
func (hc *HexColor) Scan(value interface{}) error { |
| 21 |
s, ok := value.(string) |
| 22 |
if !ok { |
| 23 |
return errUnsupportedType{got: reflect.TypeOf(value), want: reflect.TypeOf("")} |
| 24 |
} |
| 25 |
c, err := Hex(s) |
| 26 |
if err != nil { |
| 27 |
return err |
| 28 |
} |
| 29 |
*hc = HexColor(c) |
| 30 |
return nil |
| 31 |
} |
| 32 |
|
| 33 |
func (hc *HexColor) Value() (driver.Value, error) { |
| 34 |
return Color(*hc).Hex(), nil |
| 35 |
} |
| 36 |
|
| 37 |
func (hc HexColor) String() string { |
| 38 |
return Color(hc).Hex() |
| 39 |
} |
| 40 |
|
| 41 |
func (e errUnsupportedType) Error() string { |
| 42 |
return fmt.Sprintf("unsupported type: got %v, want a %s", e.got, e.want) |
| 43 |
} |
| 44 |
|
| 45 |
func (hc *HexColor) UnmarshalJSON(data []byte) error { |
| 46 |
var hexCode string |
| 47 |
if err := json.Unmarshal(data, &hexCode); err != nil { |
| 48 |
return err |
| 49 |
} |
| 50 |
|
| 51 |
var col, err = Hex(hexCode) |
| 52 |
if err != nil { |
| 53 |
return err |
| 54 |
} |
| 55 |
*hc = HexColor(col) |
| 56 |
return nil |
| 57 |
} |
| 58 |
|
| 59 |
func (hc HexColor) MarshalJSON() ([]byte, error) { |
| 60 |
return json.Marshal(Color(hc).Hex()) |
| 61 |
} |
| 62 |
|
| 63 |
// Decode - deserialize function for https://github.com/kelseyhightower/envconfig |
| 64 |
func (hc *HexColor) Decode(hexCode string) error { |
| 65 |
var col, err = Hex(hexCode) |
| 66 |
if err != nil { |
| 67 |
return err |
| 68 |
} |
| 69 |
*hc = HexColor(col) |
| 70 |
return nil |
| 71 |
} |
| 72 |
|
| 73 |
func (hc HexColor) MarshalYAML() (interface{}, error) { |
| 74 |
return Color(hc).Hex(), nil |
| 75 |
} |
| 76 |
|
| 77 |
func (hc *HexColor) UnmarshalYAML(unmarshal func(interface{}) error) error { |
| 78 |
var hexCode string |
| 79 |
if err := unmarshal(&hexCode); err != nil { |
| 80 |
return err |
| 81 |
} |
| 82 |
|
| 83 |
var col, err = Hex(hexCode) |
| 84 |
if err != nil { |
| 85 |
return err |
| 86 |
} |
| 87 |
|
| 88 |
*hc = HexColor(col) |
| 89 |
|
| 90 |
return nil |
| 91 |
} |