• Stars
    star
    1,697
  • Rank 27,502 (Top 0.6 %)
  • Language
    Go
  • License
    MIT License
  • Created about 9 years ago
  • Updated 8 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Golang Configuration tool that support YAML, JSON, TOML, Shell Environment

Configor

Golang Configuration tool that support YAML, JSON, TOML, Shell Environment (Supports Go 1.10+)

test status

Usage

package main

import (
	"fmt"
	"github.com/jinzhu/configor"
)

var Config = struct {
	APPName string `default:"app name"`

	DB struct {
		Name     string
		User     string `default:"root"`
		Password string `required:"true" env:"DBPassword"`
		Port     uint   `default:"3306"`
	}

	Contacts []struct {
		Name  string
		Email string `required:"true"`
	}
}{}

func main() {
	configor.Load(&Config, "config.yml")
	fmt.Printf("config: %#v", Config)
}

With configuration file config.yml:

appname: test

db:
    name:     test
    user:     test
    password: test
    port:     1234

contacts:
- name: i test
  email: [email protected]

Debug Mode & Verbose Mode

Debug/Verbose mode is helpful when debuging your application, debug mode will let you know how configor loaded your configurations, like from which file, shell env, verbose mode will tell you even more, like those shell environments configor tried to load.

// Enable debug mode or set env `CONFIGOR_DEBUG_MODE` to true when running your application
configor.New(&configor.Config{Debug: true}).Load(&Config, "config.json")

// Enable verbose mode or set env `CONFIGOR_VERBOSE_MODE` to true when running your application
configor.New(&configor.Config{Verbose: true}).Load(&Config, "config.json")

Auto Reload Mode

Configor can auto reload configuration based on time

// auto reload configuration every second
configor.New(&configor.Config{AutoReload: true}).Load(&Config, "config.json")

// auto reload configuration every minute
configor.New(&configor.Config{AutoReload: true, AutoReloadInterval: time.Minute}).Load(&Config, "config.json")

Auto Reload Callback

configor.New(&configor.Config{AutoReload: true, AutoReloadCallback: func(config interface{}) {
    fmt.Printf("%v changed", config)
}}).Load(&Config, "config.json")

Advanced Usage

  • Load mutiple configurations
// Earlier configurations have higher priority
configor.Load(&Config, "application.yml", "database.json")
  • Return error on unmatched keys

Return an error on finding keys in the config file that do not match any fields in the config struct. In the example below, an error will be returned if config.toml contains keys that do not match any fields in the ConfigStruct struct. If ErrorOnUnmatchedKeys is not set, it defaults to false.

Note that for json files, setting ErrorOnUnmatchedKeys to true will have an effect only if using go 1.10 or later.

err := configor.New(&configor.Config{ErrorOnUnmatchedKeys: true}).Load(&ConfigStruct, "config.toml")
  • Load configuration by environment

Use CONFIGOR_ENV to set environment, if CONFIGOR_ENV not set, environment will be development by default, and it will be test when running tests with go test

// config.go
configor.Load(&Config, "config.json")

$ go run config.go
// Will load `config.json`, `config.development.json` if it exists
// `config.development.json` will overwrite `config.json`'s configuration
// You could use this to share same configuration across different environments

$ CONFIGOR_ENV=production go run config.go
// Will load `config.json`, `config.production.json` if it exists
// `config.production.json` will overwrite `config.json`'s configuration

$ go test
// Will load `config.json`, `config.test.json` if it exists
// `config.test.json` will overwrite `config.json`'s configuration

$ CONFIGOR_ENV=production go test
// Will load `config.json`, `config.production.json` if it exists
// `config.production.json` will overwrite `config.json`'s configuration
// Set environment by config
configor.New(&configor.Config{Environment: "production"}).Load(&Config, "config.json")
  • Example Configuration
// config.go
configor.Load(&Config, "config.yml")

$ go run config.go
// Will load `config.example.yml` automatically if `config.yml` not found and print warning message
  • Load From Shell Environment
$ CONFIGOR_APPNAME="hello world" CONFIGOR_DB_NAME="hello world" go run config.go
// Load configuration from shell environment, it's name is {{prefix}}_FieldName
// You could overwrite the prefix with environment CONFIGOR_ENV_PREFIX, for example:
$ CONFIGOR_ENV_PREFIX="WEB" WEB_APPNAME="hello world" WEB_DB_NAME="hello world" go run config.go

// Set prefix by config
configor.New(&configor.Config{ENVPrefix: "WEB"}).Load(&Config, "config.json")
  • Anonymous Struct

Add the anonymous:"true" tag to an anonymous, embedded struct to NOT include the struct name in the environment variable of any contained fields. For example:

type Details struct {
	Description string
}

type Config struct {
	Details `anonymous:"true"`
}

With the anonymous:"true" tag specified, the environment variable for the Description field is CONFIGOR_DESCRIPTION. Without the anonymous:"true"tag specified, then environment variable would include the embedded struct name and be CONFIGOR_DETAILS_DESCRIPTION.

  • With flags
func main() {
	config := flag.String("file", "config.yml", "configuration file")
	flag.StringVar(&Config.APPName, "name", "", "app name")
	flag.StringVar(&Config.DB.Name, "db-name", "", "database name")
	flag.StringVar(&Config.DB.User, "db-user", "root", "database user")
	flag.Parse()

	os.Setenv("CONFIGOR_ENV_PREFIX", "-")
	configor.Load(&Config, *config)
	// configor.Load(&Config) // only load configurations from shell env & flag
}

Contributing

You can help to make the project better, check out http://gorm.io/contribute.html for things you can do.

Author

jinzhu

License

Released under the MIT License

More Repositories

1

copier

Copier for golang, copy value from struct to struct and more
Go
5,344
star
2

now

Now is a time toolkit for golang
Go
4,349
star
3

vrome

Vrome: Bringing Vim elegance to Chrome
CoffeeScript
618
star
4

inflection

Pluralizes and singularizes English nouns
Go
475
star
5

zeal-at-point

Search the word at point with Zeal (Emacs)
Emacs Lisp
166
star
6

configure

My dot files for Emacs, Openbox, XMonad, VIM, Golang, Zsh/Bash, tmux, URXVT, ArchLinux, Git, Ruby/Rails, Xbindkey, Vrome...
Emacs Lisp
89
star
7

grb

A tool to simplify working with remote git branches
Go
42
star
8

ipparse

IP Parse,Parse IP
Ruby
20
star
9

capistrano-confirm

Confirm before deploy
Ruby
16
star
10

mail

A Go Email Utility
Go
16
star
11

cacheAjax

jquery plugin to cache ajax request and more.
JavaScript
13
star
12

paygent

Ruby wrapper for paygent
Ruby
9
star
13

backupit

BackupIt: A tool to setup your backup server (backup multi servers once).
Ruby
8
star
14

yac

Yet Another Cheat
Ruby
7
star
15

mycheat

My personal cheat sheet repository for yac
6
star
16

super_list

Ruby
5
star
17

cheat

Public cheat sheet repository for yac
5
star
18

bitpay

Bitpay is a wrapper for chinese payment gateways. (unfinished, but alipay is ready to use...)
Ruby
5
star
19

cookieless

Cookieless is a rack middleware to make your application works with cookie-less devices/browsers without change your application!
Ruby
4
star
20

javascript_localize

javascript localize solution
Ruby
3
star
21

acts_as_tagtree

Tag? Tree? Tags like Tree
Ruby
3
star
22

redgreen

Ruby
2
star
23

jinzhu.github.com

My Github Page
JavaScript
2
star
24

eo

Eo_oE : EasyOperate
Ruby
2
star
25

hz_on_fly

convert hankaku to zenkaku/zenkaku to hankaku on fly
Ruby
2
star
26

acts_as_param

acts as param
Ruby
2
star
27

shanghaionrails

http://jinzhu.github.com/shanghaionrails/
2
star
28

phase_diagram

η›Έε›Ύεˆ†ζž
Ruby
2
star
29

testingmachine

Testing Machine is a automated testing tool, make keyword driven testing even easier.
Ruby
1
star
30

jquery-tab-slider

jQuery tab slider
JavaScript
1
star
31

.github

my .github
1
star
32

qLayout

JavaScript
1
star
33

devise

Ruby
1
star
34

omniauth-t163

omniauth for t163 (working)
Ruby
1
star
35

acts_as_node

Ruby
1
star
36

newplugin

newPlugin - New Plugin Generator, make it dead easy to create a new rails plugin.
Ruby
1
star
37

jslib

a collection of javascript utils
JavaScript
1
star
38

enconverter

Encoding Converter, rack middleware used to convert encoding.
Ruby
1
star