More Helper Functions

Maybe some cleanup?
This commit is contained in:
Brian Buller 2017-03-01 06:58:34 -06:00
parent acc14262cb
commit bc9246ba22
2 changed files with 37 additions and 6 deletions

View File

@ -50,6 +50,11 @@ func (c *Config) SetDateTime(k string, v time.Time) error {
return c.generalConfig.SetDateTime(k, v)
}
// SetArray saves a string slice in the <c.name>.conf file
func (c *Config) SetArray(k string, v []string) error {
return c.generalConfig.SetArray(k, v)
}
// Get at the config level retrieves a value from the <c.name>.conf file
func (c *Config) Get(k string) string {
return c.generalConfig.Get(k)
@ -72,9 +77,13 @@ func (c *Config) GetDateTime(k string) (time.Time, error) {
return c.generalConfig.GetDateTime(k)
}
func (c *Config) GetArray(k string) ([]string, error) {
return c.generalConfig.GetArray(k)
}
// DeleteKey at the config level removes a key from the <c.name>.conf file
func (c *Config) DeleteKey(k string) {
c.generalConfig.DeleteKey(k)
func (c *Config) DeleteKey(k string) error {
return c.generalConfig.DeleteKey(k)
}
// GetConfigPath just returns the config path

View File

@ -3,6 +3,7 @@ package userConfig
import (
"bytes"
"encoding/json"
"errors"
"io/ioutil"
"strconv"
@ -99,6 +100,15 @@ func (gf *GeneralConfig) SetDateTime(k string, v time.Time) error {
return gf.Set(k, v.Format(time.RFC3339))
}
// SetArray sets a string slice value (as a string) in the config file
func (gf *GeneralConfig) SetArray(k string, v []string) error {
b, e := json.Marshal(v)
if e != nil {
return e
}
return gf.SetBytes(k, b)
}
// Get gets a key/value pair from gf
func (gf *GeneralConfig) Get(k string) string {
return gf.Values[k]
@ -113,7 +123,7 @@ func (gf *GeneralConfig) GetInt(k string) (int, error) {
// GetDateTime gets a key/value pair from gf and returns it as a time.Time
// An error if it can't be converted
func (gf *GeneralConfig) GetDateTime(k string) (time.Time, error) {
return time.Parse(time.RFC3339, k)
return time.Parse(time.RFC3339, gf.Get(k))
}
// GetBytes gets a key/value pair from gf and returns it as a byte slice
@ -122,7 +132,19 @@ func (gf *GeneralConfig) GetBytes(k string) []byte {
return []byte(gf.Get(k))
}
// DeleteKey removes a key from the file
func (gf *GeneralConfig) DeleteKey(k string) {
delete(gf.Values, k)
func (gf *GeneralConfig) GetArray(k string) ([]string, error) {
var ret []string
err := json.Unmarshal(gf.GetBytes(k), &ret)
return ret, err
}
// DeleteKey removes a key from the file
func (gf *GeneralConfig) DeleteKey(k string) error {
oldVal := gf.Get(k)
delete(gf.Values, k)
if err := gf.Save(); err != nil {
gf.Values[k] = oldVal
return err
}
return nil
}