changeset 850:fcb38cedc680

More tightened color model.
author Sascha L. Teichmann <sascha.teichmann@intevation.de>
date Fri, 28 Sep 2018 12:53:08 +0200
parents d63e60b868bf
children c0bb673d360e
files pkg/controllers/system.go pkg/models/system.go
diffstat 2 files changed, 39 insertions(+), 15 deletions(-) [+]
line wrap: on
line diff
--- a/pkg/controllers/system.go	Fri Sep 28 12:35:24 2018 +0200
+++ b/pkg/controllers/system.go	Fri Sep 28 12:53:08 2018 +0200
@@ -111,10 +111,6 @@
 	attr := mux.Vars(req)["attr"]
 
 	c := input.(*models.Colour)
-	if !c.IsValid() {
-		err = JSONError{http.StatusBadRequest, "error: invalid colours"}
-		return
-	}
 
 	var res sql.Result
 	res, err = db.ExecContext(
--- a/pkg/models/system.go	Fri Sep 28 12:35:24 2018 +0200
+++ b/pkg/models/system.go	Fri Sep 28 12:53:08 2018 +0200
@@ -1,21 +1,49 @@
 package models
 
+import (
+	"database/sql/driver"
+	"encoding/json"
+	"errors"
+	"fmt"
+)
+
 type (
+	AlphaValue float64
+
 	Colour struct {
-		R int     `json:"r"`
-		G int     `json:"g"`
-		B int     `json:"b"`
-		A float32 `json:"a"`
+		R byte       `json:"r"`
+		G byte       `json:"g"`
+		B byte       `json:"b"`
+		A AlphaValue `json:"a"`
 	}
 )
 
-func isByteRange(i int) bool {
-	return i >= 0 && i < 256
+var errInvalidAlphaValue = errors.New("Invalid alpha value.")
+
+func (a *AlphaValue) UnmarshalJSON(data []byte) error {
+	var f float64
+	if err := json.Unmarshal(data, &f); err != nil {
+		return err
+	}
+	if f < 0 || f > 1 {
+		return errInvalidAlphaValue
+	}
+	*a = AlphaValue(f)
+	return nil
 }
 
-func (c Colour) IsValid() bool {
-	return isByteRange(c.R) &&
-		isByteRange(c.G) &&
-		isByteRange(c.B) &&
-		c.A >= 0 && c.A <= 1
+func (a AlphaValue) Value() (driver.Value, error) {
+	return float64(a), nil
 }
+
+func (a *AlphaValue) Scan(src interface{}) error {
+	switch v := src.(type) {
+	case int64:
+		*a = AlphaValue(v)
+	case float64:
+		*a = AlphaValue(v)
+	default:
+		return fmt.Errorf("Unexpected type %T", src)
+	}
+	return nil
+}