Config file

This commit is contained in:
Meutel 2017-08-01 15:37:58 +02:00
parent 70a2ced313
commit 0ea056a2ac
2 changed files with 45 additions and 6 deletions

1
.gitignore vendored
View File

@ -2,3 +2,4 @@
*~
go-bouquins
calibre.db
bouquins.json

50
main.go
View File

@ -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)
}