Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
working with go1, added merge functions, GetFloat, GetBool
  • Loading branch information
Patrick Crosby committed Apr 3, 2012
1 parent 040fa2f commit cb17989
Show file tree
Hide file tree
Showing 3 changed files with 69 additions and 8 deletions.
6 changes: 0 additions & 6 deletions Makefile

This file was deleted.

38 changes: 36 additions & 2 deletions config.go
Expand Up @@ -10,7 +10,7 @@ package jconfig

import (
"bytes"
"json"
"encoding/json"
"log"
"os"
)
Expand Down Expand Up @@ -47,7 +47,23 @@ func LoadConfigString(s string) *Config {
return result
}

func (c *Config) parse() os.Error {
func (c *Config) StringMerge(s string) {
next := LoadConfigString(s)
c.merge(next.data)
}

func (c *Config) LoadMerge(filename string) {
next := LoadConfig(filename)
c.merge(next.data)
}

func (c *Config) merge(ndata map[string]interface{}) {
for k, v := range ndata {
c.data[k] = v
}
}

func (c *Config) parse() error {
f, err := os.Open(c.filename)
if err != nil {
return err
Expand Down Expand Up @@ -84,6 +100,24 @@ func (c *Config) GetInt(key string) int {
return int(x.(float64))
}

// Returns a float for the config variable key
func (c *Config) GetFloat(key string) float64 {
x, ok := c.data[key]
if !ok {
return -1
}
return x.(float64)
}

// Returns a bool for the config variable key
func (c *Config) GetBool(key string) bool {
x, ok := c.data[key]
if !ok {
return false
}
return x.(bool)
}

// Returns an array for the config variable key
func (c *Config) GetArray(key string) []interface{} {
result, present := c.data[key]
Expand Down
33 changes: 33 additions & 0 deletions config_test.go
Expand Up @@ -22,3 +22,36 @@ func TestConfigFromString(t *testing.T) {
t.Errorf("expected 3 elt array")
}
}

func TestConfigBool(t *testing.T) {
c := LoadConfigString(`{"istrue":true,"isfalse":false}`)
if c == nil {
t.Fatalf("expected a config object")
}
if c.GetBool("istrue") == false {
t.Errorf("expected true")
}
if c.GetBool("isfalse") == true {
t.Errorf("expected false")
}
}

func TestConfigMerge(t *testing.T) {
c := LoadConfigString(`{"one":1,"two":"zwei","three":["a","b","c"]}`)
if c == nil {
t.Fatalf("expected a config object")
}
c.StringMerge(`{"two":2,"four":"vier"}`)
if c.GetInt("one") != 1 {
t.Errorf("expected 1, got %d:", c.GetInt("one"))
}
if len(c.GetArray("three")) != 3 {
t.Errorf("expected 3 elt array")
}
if c.GetInt("two") != 2 {
t.Errorf("expected 2, got %d:", c.GetInt("two"))
}
if c.GetString("four") != "vier" {
t.Errorf("expected vier, got %s:", c.GetString("four"))
}
}

0 comments on commit cb17989

Please sign in to comment.