Last active
May 1, 2018 18:25
-
-
Save lpar/889663b92ce56bfb562fcb53e52fd9ad to your computer and use it in GitHub Desktop.
Very simple example of reading a config file into an object which provides an interface for fetching config values
This file contains 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 ( | |
"bufio" | |
"fmt" | |
"os" | |
"strings" | |
) | |
type Config interface { | |
Get(string) (string, error) | |
} | |
type AppConfig struct { | |
data map[string]string | |
} | |
func (ac AppConfig) Get(key string) (string, error) { | |
value, ok := ac.data[key] | |
if !ok { | |
return "", fmt.Errorf("attempt to read nonexistent config value %s", key) | |
} | |
return value, nil | |
} | |
func NewAppConfig(filename string) AppConfig { | |
fin, err := os.Open(filename) | |
if err != nil { | |
panic("error opening config file: " + err.Error()) | |
} | |
defer func() { | |
cerr := fin.Close() | |
if cerr != nil { | |
panic("error closing config file: " + cerr.Error()) | |
} | |
}() | |
scanner := bufio.NewScanner(fin) | |
scanner.Split(bufio.ScanLines) | |
config := AppConfig{} | |
config.data = make(map[string]string, 0) | |
for scanner.Scan() { | |
line := scanner.Text() | |
chunks := strings.Split(line, "=") | |
if len(chunks) == 2 { | |
config.data[chunks[0]] = chunks[1] | |
} | |
} | |
return config | |
} | |
func dumpConfig(conf Config) { | |
x, err := conf.Get("keyname") | |
if err != nil { | |
panic(err) | |
} | |
fmt.Println("keyname = " + x) | |
x, err = conf.Get("invalidkey") | |
if err != nil { | |
panic(err) | |
} | |
fmt.Println("invalidkey = " + x) | |
} | |
func main() { | |
config := NewAppConfig("configfile.txt") | |
dumpConfig(config) | |
} |
This file contains 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
keyname=My value | |
otherkey=Something else |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment