Last active
September 16, 2024 21:17
-
-
Save havlan/b73c3512a8267be4b987e11957894bd2 to your computer and use it in GitHub Desktop.
Loading json config files in golang, useful for database type configs.
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
| /* | |
| layout of config file | |
| { | |
| "host":"localhost", | |
| "port": 5432, | |
| "user": "postgres", | |
| "password": "123123", | |
| "database": "example_db" | |
| } | |
| */ | |
| package main | |
| type Config struct { | |
| Host string `json:"host"` | |
| Port int `json:"port"` | |
| User string `json:"user"` | |
| Password string `json:"password"` | |
| Database string `json:"database"` | |
| } | |
| func (c Config) String() string { | |
| return fmt.Sprintf("%s, %d, %s, %s", c.Host, c.Port, c.User, c.Database) | |
| } | |
| func NewConfig(filename string) (Config, error) { | |
| var cf Config | |
| confFile, err := os.Open("./" + filename) // if the file is in the same directory | |
| defer confFile.Close() | |
| if err != nil { | |
| return cf, err | |
| } | |
| jsonParser := json.NewDecoder(confFile) | |
| jsonParser.Decode(&cf) | |
| if err != nil { | |
| return cf, err | |
| } | |
| return cf, nil | |
| } | |
| func main() { | |
| var cfg, err = NewConfig("config.json") | |
| fmt.Println(err) // prints nil | |
| fmt.Println(cfg) // prints the objects String() method. | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment