gemini-browser

A text-based gemini browser
git clone git://git.laack.co/gemini-browser.git
Log | Files | Refs | README

hexcolor.go (1412B)


      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 (e errUnsupportedType) Error() string {
     38 	return fmt.Sprintf("unsupported type: got %v, want a %s", e.got, e.want)
     39 }
     40 
     41 func (hc *HexColor) UnmarshalJSON(data []byte) error {
     42 	var hexCode string
     43 	if err := json.Unmarshal(data, &hexCode); err != nil {
     44 		return err
     45 	}
     46 
     47 	var col, err = Hex(hexCode)
     48 	if err != nil {
     49 		return err
     50 	}
     51 	*hc = HexColor(col)
     52 	return nil
     53 }
     54 
     55 func (hc HexColor) MarshalJSON() ([]byte, error) {
     56 	return json.Marshal(Color(hc).Hex())
     57 }
     58 
     59 // Decode - deserialize function for https://github.com/kelseyhightower/envconfig
     60 func (hc *HexColor) Decode(hexCode string) error {
     61 	var col, err = Hex(hexCode)
     62 	if err != nil {
     63 		return err
     64 	}
     65 	*hc = HexColor(col)
     66 	return nil
     67 }