From 0ea056a2acc8a441d60590ad91d9fff9ba9719f6 Mon Sep 17 00:00:00 2001 From: Meutel Date: Tue, 1 Aug 2017 15:37:58 +0200 Subject: [PATCH] Config file --- .gitignore | 1 + main.go | 50 ++++++++++++++++++++++++++++++++++++++++++++------ 2 files changed, 45 insertions(+), 6 deletions(-) diff --git a/.gitignore b/.gitignore index 4a3d7e4..3800f46 100644 --- a/.gitignore +++ b/.gitignore @@ -2,3 +2,4 @@ *~ go-bouquins calibre.db +bouquins.json diff --git a/main.go b/main.go index c9d28c3..0fd43e2 100644 --- a/main.go +++ b/main.go @@ -2,20 +2,27 @@ package main import ( "database/sql" + "encoding/json" "html/template" "log" "net/http" + "os" _ "github.com/mattn/go-sqlite3" "meutel.net/meutel/go-bouquins/bouquins" ) +type BouquinsConf struct { + BindAddress string `json:"bind-address"` + DbPath string `json:"db-path"` +} + const ( INDEX = "/" - BOOKS = "/books" - AUTHORS = "/authors" - SERIES = "/series" + BOOKS = "/books/" + AUTHORS = "/authors/" + SERIES = "/series/" JS = "/js/" CSS = "/css/" FONTS = "/fonts/" @@ -23,13 +30,42 @@ const ( var db *sql.DB -func init() { +// load config +func ReadConfig() (*BouquinsConf, error) { + conf := new(BouquinsConf) + confPath := "bouquins.json" + if len(os.Args) > 1 { + confPath = os.Args[1] + } + confFile, err := os.Open(confPath) + if err == nil { + defer confFile.Close() + err = json.NewDecoder(confFile).Decode(conf) + } else { + log.Println("no conf file, using defaults") + err = nil + } + // default values + if conf.DbPath == "" { + conf.DbPath = "calibre.db" + } + if conf.BindAddress == "" { + conf.BindAddress = ":9000" + } + return conf, err +} + +func initApp() *BouquinsConf { log.SetFlags(log.LstdFlags | log.Lshortfile) + conf, err := ReadConfig() + if err != nil { + log.Fatalln(err) + } tpl, err := template.ParseGlob("templates/*.html") if err != nil { log.Fatalln(err) } - db, err = sql.Open("sqlite3", "calibre.db") + db, err = sql.Open("sqlite3", conf.DbPath) if err != nil { log.Fatalln(err) } @@ -39,6 +75,7 @@ func init() { } assets() router(app) + return conf } func assets() { @@ -55,6 +92,7 @@ func router(app *bouquins.Bouquins) { } func main() { + conf := initApp() defer db.Close() - http.ListenAndServe(":9000", nil) + http.ListenAndServe(conf.BindAddress, nil) }