env_json

package module
v0.0.0-...-8615008 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 3, 2015 License: Apache-2.0 Imports: 2 Imported by: 4

README

ENV JSON

this package based on github.com/gogap/env_strings

Read Env from config and compile the values into json file.

About ENV JSON

Sometimes we need config file as following:

db.conf

{
	"host":"127.0.0.1",
	"password":"3306",
	"timeout": 1000
}

but, when we management more and more server and serivce, and if we need change the password or ip, it was a disaster.

So, we just want use config like this.

db.conf

{
	"host":"{{.host}}",
	"password":"{{.password}}",
	"timeout":{{.timeout}}
}

We use golang's template to replace values into the config while we read the json file configs.

first, we set the env config at ~/.bash_profile or ~/.zshrc, and the default key is ENV_JSON and the default file extention is .env, the value of ENV_JSON could be a file or folder,it joined by;, it will automatic load all *.env files.

Env

export ENV_JSON='~/playgo/test.env;~/playgo/test2.env'

or

export ENV_JSON='~/playgo'
example program
package main

import (
	"fmt"
	"io/ioutil"

	"github.com/gogap/env_json"
)

type DBConfig struct {
	Host     string `json:"host"`
	Password string `json:"password"`
	Timeout  int64  `json:timeout`
}

func main() {
	data, _ := ioutil.ReadFile("./db.conf")

	dbConf := DBConfig{}

	if err := env_json.Unmarshal(data, &dbConf); err != nil {
		fmt.Print(err)
		return
	}

	fmt.Println(dbConf)
}

env1.json

{
	"host":"127.0.0.1",
	"password":"123456"
}

env2.json

{
	"timeout":1000
}

result:

{127.0.0.1 123456 1000}
More

if you want use your own ENV key, you could do it like this

envJson := NewEnvJson("YOUR_ENV_KEY_NAME", ".json")
envJson.Unmarshal(data, &dbConf);

Documentation

Index

Constants

View Source
const (
	ENV_JSON_KEY = "ENV_JSON"
	ENV_JSON_EXT = ".env"
)

Variables

This section is empty.

Functions

func Marshal

func Marshal(v interface{}) ([]byte, error)

func MarshalIndent

func MarshalIndent(v interface{}, prefix, indent string) ([]byte, error)

func Unmarshal

func Unmarshal(data []byte, v interface{}) error

Types

type EnvJson

type EnvJson struct {
	*env_strings.EnvStrings
}

func NewEnvJson

func NewEnvJson(envName string, envExt string) *EnvJson

func (*EnvJson) Marshal

func (p *EnvJson) Marshal(v interface{}) (data []byte, err error)

func (*EnvJson) MarshalIndent

func (p *EnvJson) MarshalIndent(v interface{}, prefix, indent string) ([]byte, error)

func (*EnvJson) Unmarshal

func (p *EnvJson) Unmarshal(data []byte, v interface{}) (err error)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL