added config file support
parent
c7d5e4be87
commit
aabda1cc90
@ -0,0 +1,60 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"log"
|
||||
"os"
|
||||
"os/user"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
Tick int `json:"tick"` // ms
|
||||
Timescale float32 `json:"timescale"`
|
||||
Width int `json:"width"`
|
||||
Height int `json:"height"`
|
||||
Obstacles int `json:"obstacles"`
|
||||
}
|
||||
|
||||
const (
|
||||
TICK = 60
|
||||
TIMESCALE = 1.0
|
||||
WIDTH = 800
|
||||
HEIGHT = 550
|
||||
OBSTACLES = 5
|
||||
)
|
||||
|
||||
func loadConfig(filename string) (Config, error) {
|
||||
c := Config{}
|
||||
u, err := user.Current()
|
||||
if err != nil {
|
||||
return c, err
|
||||
}
|
||||
if len(filename) > 1 && filename[:2] == "~/" {
|
||||
filename = strings.Replace(filename, "~", u.HomeDir, 1)
|
||||
}
|
||||
if _, err := os.Stat(filename); os.IsNotExist(err) {
|
||||
log.Printf("%+v not found, using defaults", filename)
|
||||
return Config{
|
||||
Tick: TICK,
|
||||
Timescale: TIMESCALE,
|
||||
Width: WIDTH,
|
||||
Height: HEIGHT,
|
||||
Obstacles: OBSTACLES,
|
||||
}, nil
|
||||
} else {
|
||||
log.Printf("found config file: %s", filename)
|
||||
f, err := ioutil.ReadFile(filename)
|
||||
if err != nil {
|
||||
return c, err
|
||||
}
|
||||
err = json.Unmarshal(f, &c)
|
||||
if err != nil {
|
||||
return c, errors.New(fmt.Sprintf("config parse error: %s", err))
|
||||
}
|
||||
}
|
||||
return c, nil
|
||||
}
|
Loading…
Reference in New Issue