Skip to content

Instantly share code, notes, and snippets.

@Pepeye
Last active June 12, 2018 16:15
Show Gist options
  • Save Pepeye/2906c07775a6a25e2a9ab6af96b26375 to your computer and use it in GitHub Desktop.
Save Pepeye/2906c07775a6a25e2a9ab6af96b26375 to your computer and use it in GitHub Desktop.
Golang & JSON config files
package main
import (
"encoding/json"
"fmt"
"os"
"time"
"github.com/rs/xid"
)
// set global config variable
var conf *Config
// create config struct
type Config struct {
ID xid.ID `json:"id"`
Server struct {
Port int `json:"port"`
} `json:"server"`
Database struct {
Name string `json:"name"`
URL string `json:"url"`
} `json:"database"`
CreatedAt int64 `json:"createdat"`
}
func main() {
file, err := os.Open("config.json")
if err != nil {
fmt.Printf("[ERROR] Opening File - : %s", err)
}
err = json.NewDecoder(file).Decode(&conf)
if err != nil {
fmt.Printf("[ERROR] Decoding File - : %s", err)
}
conf.ID = xid.New()
conf.CreatedAt = time.Now().UnixNano()
PrettyPrint(conf)
// fmt.Printf("%+v", conf)
}
// PrettyPrint - displays indented JSON
func PrettyPrint(v interface{}) (err error) {
b, err := json.MarshalIndent(v, "", " ")
if err == nil {
fmt.Println(string(b))
}
return
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment