Skip to content

Commit

Permalink
Add json and envconfig serialization support for HexColor (#42)
Browse files Browse the repository at this point in the history
  • Loading branch information
alikhil authored Jan 27, 2021
1 parent d49a4a4 commit 9be4ace
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 1 deletion.
32 changes: 31 additions & 1 deletion hexcolor.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,14 @@ 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 and database/sql/driver.Value interfaces.
// database/sql.Scanner, database/sql/driver.Value,
// encoding/json.Unmarshaler and encoding/json.Marshaler interfaces.
type HexColor Color

type errUnsupportedType struct {
Expand Down Expand Up @@ -35,3 +37,31 @@ func (hc *HexColor) Value() (driver.Value, error) {
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 - deserilize 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
}
25 changes: 25 additions & 0 deletions hexcolor_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package colorful

import (
"encoding/json"
"reflect"
"testing"
)
Expand Down Expand Up @@ -28,3 +29,27 @@ func TestHexColor(t *testing.T) {
}
}
}

type CompositeType struct {
Name string `json:"name,omitempty"`
Color HexColor `json:"color,omitempty"`
}

func TestHexColorCompositeJson(t *testing.T) {
var obj = CompositeType{Name: "John", Color: HexColor{R: 1, G: 0, B: 1}}
var jsonData, err = json.Marshal(obj)
if err != nil {
t.Errorf("json.Marshall(obj) wrote %v", err)
}
var obj2 CompositeType
err = json.Unmarshal(jsonData, &obj2)

if err != nil {
t.Errorf("json.Unmarshall(%s) wrote %v", jsonData, err)
}

if !reflect.DeepEqual(obj2, obj) {
t.Errorf("json.Unmarshal(json.Marsrhall(obj)) != obj")
}

}

0 comments on commit 9be4ace

Please sign in to comment.