Last active
June 12, 2018 16:15
-
-
Save Pepeye/2906c07775a6a25e2a9ab6af96b26375 to your computer and use it in GitHub Desktop.
Golang & JSON config files
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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