├── .github └── workflows │ └── go.yml ├── LICENSE ├── README.md ├── config.go ├── config_test.go ├── examples └── hello-world │ ├── config.json │ └── main.go ├── go.mod ├── invalid.json └── test.json /.github/workflows/go.yml: -------------------------------------------------------------------------------- 1 | name: Go 2 | on: [push] 3 | jobs: 4 | 5 | build: 6 | name: Build 7 | runs-on: ubuntu-latest 8 | steps: 9 | 10 | - name: Set up Go 1.13 11 | uses: actions/setup-go@v1 12 | with: 13 | go-version: 1.13 14 | id: go 15 | 16 | - name: Check out code into the Go module directory 17 | uses: actions/checkout@v1 18 | 19 | - name: Get dependencies 20 | run: | 21 | go get -u golang.org/x/lint/golint 22 | go get -v -t -d ./... 23 | if [ -f Gopkg.toml ]; then 24 | curl https://raw.githubusercontent.com/golang/dep/master/install.sh | sh 25 | dep ensure 26 | fi 27 | 28 | - name: Build 29 | run: go build -v . 30 | 31 | - name: Test 32 | run: | 33 | go vet ./... 34 | test -z "$(gofmt -s -l . | grep -v vendor | tee /dev/stderr)" 35 | test -z "$(golint ./... | grep -v vendor | tee /dev/stderr)" 36 | go test -v ./... 37 | 38 | - name: Bench 39 | run: go test -bench=. 40 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2017 Josh Betz 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # config 2 | 3 | [![Build Status](https://travis-ci.org/joshbetz/config.svg?branch=master)](https://travis-ci.org/joshbetz/config) [![Go Report Card](https://goreportcard.com/badge/github.com/joshbetz/config)](https://goreportcard.com/report/github.com/joshbetz/config) [![](https://godoc.org/github.com/joshbetz/config?status.svg)](http://godoc.org/github.com/joshbetz/config) 4 | 5 | 6 | A small configuration library for Go that parses environment variables, JSON 7 | files, and reloads automatically on `SIGHUP`. 8 | 9 | ## Example 10 | 11 | ```go 12 | func main() { 13 | c := config.New("config.json") 14 | 15 | http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { 16 | var value string 17 | c.Get("value", &value) 18 | fmt.Fprintf(w, "Value: %s", value) 19 | }) 20 | 21 | http.ListenAndServe(":3000", nil) 22 | } 23 | ``` 24 | 25 | ![Reload config on SIGHUP](http://i.imgur.com/6H8b6zy.gif) 26 | 27 | ## API 28 | 29 | ```go 30 | func New(file string) *Config 31 | ``` 32 | 33 | Constructor that initializes a Config object and sets up the SIGHUP watcher. 34 | 35 | ```go 36 | func (config *Config) Get(key string, v interface{}) error 37 | ``` 38 | 39 | Takes the path to a JSON file, the name of the configuration option, and a 40 | pointer to the variable where the config value will be stored. `v` can be a 41 | pointer to a string, bool, or float64. 42 | 43 | ```go 44 | func (config *Config) Reload() 45 | ``` 46 | 47 | Reloads the config. Happens automatically on `SIGHUP`. 48 | -------------------------------------------------------------------------------- /config.go: -------------------------------------------------------------------------------- 1 | package config 2 | 3 | import ( 4 | "encoding/json" 5 | "errors" 6 | "io/ioutil" 7 | "log" 8 | "os" 9 | "os/signal" 10 | "strconv" 11 | "syscall" 12 | ) 13 | 14 | // Config represents a configuration file. 15 | type Config struct { 16 | filename string 17 | cache *map[string]interface{} 18 | } 19 | 20 | // New creates a new Config object. 21 | func New(filename string) *Config { 22 | config := Config{filename, nil} 23 | config.Reload() 24 | go config.watch() 25 | return &config 26 | } 27 | 28 | // Get retreives a Config option into a passed in pointer or returns an error. 29 | func (config *Config) Get(key string, v interface{}) error { 30 | var val interface{} 31 | 32 | env, set := os.LookupEnv(key) 33 | 34 | if set { 35 | switch v.(type) { 36 | case *float64: 37 | val, err := strconv.ParseFloat(env, 64) 38 | 39 | if err != nil { 40 | return err 41 | } 42 | 43 | *v.(*float64) = val 44 | return nil 45 | case *int: 46 | val, err := strconv.ParseInt(env, 10, 64) 47 | 48 | if err != nil { 49 | return err 50 | } 51 | 52 | *v.(*int) = int(val) 53 | return nil 54 | default: 55 | val = env 56 | } 57 | } else if config.cache != nil { 58 | val = (*config.cache)[key] 59 | } 60 | 61 | // Cast JSON values 62 | switch v.(type) { 63 | case *string: 64 | if val == nil { 65 | val = "" 66 | } 67 | 68 | if b, ok := val.(bool); ok { 69 | *v.(*string) = strconv.FormatBool(b) 70 | } else if f, ok := val.(float64); ok { 71 | *v.(*string) = strconv.FormatFloat(f, 'f', -1, 64) 72 | } else { 73 | *v.(*string) = val.(string) 74 | } 75 | case *bool: 76 | switch val { 77 | case nil, 0, false, "", "0", "false": 78 | // falsey 79 | val = false 80 | default: 81 | // truthy 82 | val = true 83 | } 84 | 85 | *v.(*bool) = val.(bool) 86 | case *float64: 87 | if val == nil { 88 | val = float64(0) 89 | } 90 | 91 | if s, ok := val.(string); ok { 92 | pf, err := strconv.ParseFloat(s, 64) 93 | if err != nil { 94 | return err 95 | } 96 | 97 | *v.(*float64) = pf 98 | } else { 99 | *v.(*float64) = val.(float64) 100 | } 101 | case *int: 102 | if val == nil { 103 | val = float64(0) 104 | } 105 | 106 | *v.(*int) = int(val.(float64)) 107 | default: 108 | return errors.New("Type not supported") 109 | } 110 | 111 | return nil 112 | } 113 | 114 | // Reload clears the config cache. 115 | func (config *Config) Reload() error { 116 | cache, err := primeCacheFromFile(config.filename) 117 | config.cache = cache 118 | 119 | if err != nil { 120 | return err 121 | } 122 | 123 | return nil 124 | } 125 | 126 | func (config *Config) watch() { 127 | l := log.New(os.Stderr, "", 0) 128 | 129 | // Catch SIGHUP to automatically reload cache 130 | sighup := make(chan os.Signal, 1) 131 | signal.Notify(sighup, syscall.SIGHUP) 132 | 133 | for { 134 | <-sighup 135 | l.Println("Caught SIGHUP, reloading config...") 136 | config.Reload() 137 | } 138 | } 139 | 140 | func primeCacheFromFile(file string) (*map[string]interface{}, error) { 141 | // File exists? 142 | if _, err := os.Stat(file); os.IsNotExist(err) { 143 | return nil, err 144 | } 145 | 146 | // Read file 147 | raw, err := ioutil.ReadFile(file) 148 | if err != nil { 149 | return nil, err 150 | } 151 | 152 | // Unmarshal 153 | var config map[string]interface{} 154 | if err := json.Unmarshal(raw, &config); err != nil { 155 | return nil, err 156 | } 157 | 158 | return &config, nil 159 | } 160 | -------------------------------------------------------------------------------- /config_test.go: -------------------------------------------------------------------------------- 1 | package config 2 | 3 | import ( 4 | "testing" 5 | 6 | "os" 7 | ) 8 | 9 | func BenchmarkGet(b *testing.B) { 10 | c := New("test.json") 11 | 12 | var v string 13 | for i := 0; i < b.N; i++ { 14 | c.Get("test", &v) 15 | } 16 | } 17 | 18 | func TestGet(t *testing.T) { 19 | c := New("test.json") 20 | 21 | t.Run("Get", func(t *testing.T) { 22 | t.Run("should successfully retrieve string", func(t *testing.T) { 23 | var s string 24 | 25 | err := c.Get("string", &s) 26 | if err != nil { 27 | t.Error(err) 28 | } 29 | 30 | if s != "asdf" { 31 | t.Errorf("Expected 'asdf', got '%v'", s) 32 | } 33 | }) 34 | 35 | t.Run("should successfully cast empty value to string", func(t *testing.T) { 36 | var s string 37 | 38 | err := c.Get("nonexistant", &s) 39 | if err != nil { 40 | t.Error(err) 41 | } 42 | 43 | if s != "" { 44 | t.Errorf("Expected '', got '%v'", s) 45 | } 46 | }) 47 | 48 | t.Run("should successfully cast bool to string", func(t *testing.T) { 49 | var s string 50 | 51 | err := c.Get("bool", &s) 52 | if err != nil { 53 | t.Error(err) 54 | } 55 | 56 | if s != "true" { 57 | t.Errorf("Expect 'true', got '%v'", s) 58 | } 59 | }) 60 | 61 | t.Run("should successfully cast float to string", func(t *testing.T) { 62 | var s string 63 | 64 | err := c.Get("float64", &s) 65 | if err != nil { 66 | t.Error(err) 67 | } 68 | 69 | if s != "64.4" { 70 | t.Errorf("Expect '64.4', got '%v'", s) 71 | } 72 | }) 73 | 74 | t.Run("should successfully retrieve bool", func(t *testing.T) { 75 | var b bool 76 | 77 | err := c.Get("bool", &b) 78 | if err != nil { 79 | t.Error(err) 80 | } 81 | 82 | if b != true { 83 | t.Errorf("Expected 'true', got '%v'", b) 84 | } 85 | }) 86 | 87 | t.Run("should successfully cast string to bool", func(t *testing.T) { 88 | var b bool 89 | 90 | err := c.Get("string", &b) 91 | if err != nil { 92 | t.Error(err) 93 | } 94 | 95 | if b != true { 96 | t.Errorf("Expected 'true', got '%v'", b) 97 | } 98 | }) 99 | 100 | t.Run("should successfully cast empty value to bool", func(t *testing.T) { 101 | var b bool 102 | 103 | err := c.Get("nonexistant", &b) 104 | if err != nil { 105 | t.Error(err) 106 | } 107 | 108 | if b != false { 109 | t.Errorf("Expected 'false', got '%v'", b) 110 | } 111 | }) 112 | 113 | t.Run("should successfully cast float to bool", func(t *testing.T) { 114 | var b bool 115 | 116 | // truthy 117 | err := c.Get("float64", &b) 118 | if err != nil { 119 | t.Error(err) 120 | } 121 | 122 | if b != true { 123 | t.Errorf("Expected 'true', got '%v'", b) 124 | } 125 | 126 | // falsey 127 | err = c.Get("falsey", &b) 128 | if err != nil { 129 | t.Error(err) 130 | } 131 | 132 | if b != false { 133 | t.Errorf("Expected 'false', got '%v'", b) 134 | } 135 | }) 136 | 137 | t.Run("should successfully retrieve float64", func(t *testing.T) { 138 | var f float64 139 | 140 | err := c.Get("float64", &f) 141 | if err != nil { 142 | t.Error(err) 143 | } 144 | 145 | if f != 64.4 { 146 | t.Errorf("Expected '64.4', got '%v'", f) 147 | } 148 | }) 149 | 150 | t.Run("should successfully cast empty value to float64", func(t *testing.T) { 151 | var f float64 152 | 153 | err := c.Get("nonexistant", &f) 154 | if err != nil { 155 | t.Error(err) 156 | } 157 | 158 | if f != 0 { 159 | t.Errorf("Expected '0', got '%v'", f) 160 | } 161 | }) 162 | 163 | t.Run("should successfully cast string to float", func(t *testing.T) { 164 | var f float64 165 | 166 | err := c.Get("string2", &f) 167 | if err != nil { 168 | t.Error(err) 169 | } 170 | 171 | if f != 13.37 { 172 | t.Errorf("Expect '13.37', got '%v'", f) 173 | } 174 | 175 | err = c.Get("string3", &f) 176 | if err != nil { 177 | t.Error(err) 178 | } 179 | 180 | if f != 0.0 { 181 | t.Errorf("Expect '0.0', got '%v'", f) 182 | } 183 | }) 184 | 185 | t.Run("should successfully override with Env", func(t *testing.T) { 186 | var s string 187 | 188 | err := os.Setenv("string", "abcd") 189 | if err != nil { 190 | t.Error(err) 191 | } 192 | 193 | err = c.Get("string", &s) 194 | if err != nil { 195 | t.Error(err) 196 | } 197 | 198 | if s != "abcd" { 199 | t.Errorf("Expected 'abcd', got '%v'", s) 200 | } 201 | }) 202 | 203 | t.Run("should correctly cast env to float64", func(t *testing.T) { 204 | var f float64 205 | 206 | err := os.Setenv("float64-2", "50") 207 | if err != nil { 208 | t.Error(err) 209 | } 210 | 211 | err = c.Get("float64-2", &f) 212 | if err != nil { 213 | t.Error(err) 214 | } 215 | 216 | if f != 50 { 217 | t.Errorf("Expected '50', got '%v'", f) 218 | } 219 | }) 220 | 221 | t.Run("should correctly cast env to int", func(t *testing.T) { 222 | var i int 223 | 224 | err := os.Setenv("int", "50") 225 | if err != nil { 226 | t.Error(err) 227 | } 228 | 229 | err = c.Get("int", &i) 230 | if err != nil { 231 | t.Error(err) 232 | } 233 | 234 | if i != 50 { 235 | t.Errorf("Expected '50', got '%v'", i) 236 | } 237 | }) 238 | 239 | t.Run("should successfully cast float to int", func(t *testing.T) { 240 | var i int 241 | 242 | err := c.Get("float64", &i) 243 | if err != nil { 244 | t.Error(err) 245 | } 246 | 247 | if i != 64 { 248 | t.Errorf("Expected '64', got '%v'", i) 249 | } 250 | }) 251 | 252 | t.Run("should correctly cast empty value to int", func(t *testing.T) { 253 | var i int 254 | 255 | err := c.Get("nonexistant", &i) 256 | if err != nil { 257 | t.Error(err) 258 | } 259 | 260 | if i != 0 { 261 | t.Errorf("Expected '0', got '%v'", i) 262 | } 263 | }) 264 | 265 | t.Run("should correctly error for invalid types", func(t *testing.T) { 266 | var r rune 267 | 268 | err := c.Get("float64", &r) 269 | if err == nil { 270 | t.Error("Expected an error, got nil") 271 | } 272 | }) 273 | 274 | t.Run("should correctly error for nonexistant files", func(t *testing.T) { 275 | c2 := New("nonexistant.json") 276 | err := c2.Reload() 277 | if err == nil { 278 | t.Error("Expected an error, got nil") 279 | } 280 | }) 281 | 282 | t.Run("should correctly error for invalid files", func(t *testing.T) { 283 | c2 := New("invalid.json") 284 | err := c2.Reload() 285 | if err == nil { 286 | t.Error("Expected an error, got nil") 287 | } 288 | }) 289 | }) 290 | } 291 | -------------------------------------------------------------------------------- /examples/hello-world/config.json: -------------------------------------------------------------------------------- 1 | { 2 | "value": "abcd" 3 | } 4 | -------------------------------------------------------------------------------- /examples/hello-world/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | "net/http" 7 | 8 | "github.com/joshbetz/config" 9 | ) 10 | 11 | func main() { 12 | c := config.New("config.json") 13 | 14 | http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { 15 | var value string 16 | err := c.Get("value", &value) 17 | 18 | if err != nil { 19 | fmt.Fprintf(w, "Error: %s\n", err) 20 | return 21 | } 22 | 23 | fmt.Fprintf(w, "Value: %s\n", value) 24 | }) 25 | 26 | log.Fatal(http.ListenAndServe(":3000", nil)) 27 | } 28 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/joshbetz/config 2 | 3 | go 1.12 4 | -------------------------------------------------------------------------------- /invalid.json: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/joshbetz/config/121804b392d9d25f68b05a8c3456822addc4c7d8/invalid.json -------------------------------------------------------------------------------- /test.json: -------------------------------------------------------------------------------- 1 | { 2 | "string": "asdf", 3 | "bool": true, 4 | "float64": 64.4, 5 | "falsey": "false", 6 | "string2": "13.37", 7 | "string3": "0.0" 8 | } 9 | --------------------------------------------------------------------------------