Mercurial > gemma
diff pkg/common/attributes.go @ 2036:74e24ae3205a unify_imports
Imports: Added a persistent model for the extra attributes.
author | Sascha L. Teichmann <sascha.teichmann@intevation.de> |
---|---|
date | Fri, 25 Jan 2019 11:52:54 +0100 |
parents | 8eeb0b5eb340 |
children | 78002c5e838c |
line wrap: on
line diff
--- a/pkg/common/attributes.go Fri Jan 25 11:26:20 2019 +0100 +++ b/pkg/common/attributes.go Fri Jan 25 11:52:54 2019 +0100 @@ -20,9 +20,31 @@ "time" ) -// Attributes is a map of optional key/value attributes -// of a configuration. -type Attributes map[string]string +type ( + + // Attributes is a map of optional key/value attributes + // of a configuration. + Attributes map[string]string + + AttributesMarshaler interface { + MarshalAttributes(Attributes) error + } + + AttributesUnmarshaler interface { + UnmarshalAttributes(Attributes) error + } +) + +func (ca Attributes) Delete(key string) bool { + if ca == nil { + return false + } + if _, found := ca[key]; !found { + return false + } + delete(ca, key) + return true +} // Get fetches a value for given key out of the configuration. // If the key was not found the bool component of the return value @@ -35,19 +57,39 @@ return value, found } +func (ca Attributes) Set(key, value string) bool { + if ca == nil { + return false + } + ca[key] = value + return true +} + // Bool returns a bool value for a given key. func (ca Attributes) Bool(key string) bool { s, found := ca.Get(key) return found && strings.ToLower(s) == "true" } +func (ca Attributes) SetBool(key string, value bool) bool { + var v string + if value { + v = "true" + } else { + v = "false" + } + return ca.Set(key, v) +} + +const TimeFormat = "2006-01-02T15:04:05" + // Time gives a time.Time for a given key. func (ca Attributes) Time(key string) (time.Time, bool) { s, found := ca.Get(key) if !found { return time.Time{}, false } - t, err := time.Parse("2006-01-02T15:04:05", s) + t, err := time.Parse(TimeFormat, s) if err != nil { log.Printf("error: %v\n", err) return time.Time{}, false @@ -55,6 +97,12 @@ return t, true } +func (ca Attributes) SetTime(key string, t time.Time) bool { + value := t.Format(TimeFormat) + return ca.Set(key, value) + +} + func (ca Attributes) Int(key string) (int, bool) { s, found := ca.Get(key) if !found { @@ -68,6 +116,11 @@ return i, true } +func (ca Attributes) SetInt(key string, value int) bool { + v := strconv.Itoa(value) + return ca.Set(key, v) +} + func (ca Attributes) Duration(key string) (time.Duration, bool) { s, found := ca.Get(key) if !found { @@ -80,3 +133,8 @@ } return d, true } + +func (ca Attributes) SetDuration(key string, value time.Duration) bool { + v := value.String() + return ca.Set(key, v) +}