Skip to content

Instantly share code, notes, and snippets.

@lpar
Last active May 1, 2018 18:25
Show Gist options
  • Save lpar/889663b92ce56bfb562fcb53e52fd9ad to your computer and use it in GitHub Desktop.
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
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)
}
keyname=My value
otherkey=Something else
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment