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 go-bouquins
calibre.db calibre.db
bouquins.json

50
main.go
View File

@ -2,20 +2,27 @@ package main
import ( import (
"database/sql" "database/sql"
"encoding/json"
"html/template" "html/template"
"log" "log"
"net/http" "net/http"
"os"
_ "github.com/mattn/go-sqlite3" _ "github.com/mattn/go-sqlite3"
"meutel.net/meutel/go-bouquins/bouquins" "meutel.net/meutel/go-bouquins/bouquins"
) )
type BouquinsConf struct {
BindAddress string `json:"bind-address"`
DbPath string `json:"db-path"`
}
const ( const (
INDEX = "/" INDEX = "/"
BOOKS = "/books" BOOKS = "/books/"
AUTHORS = "/authors" AUTHORS = "/authors/"
SERIES = "/series" SERIES = "/series/"
JS = "/js/" JS = "/js/"
CSS = "/css/" CSS = "/css/"
FONTS = "/fonts/" FONTS = "/fonts/"
@ -23,13 +30,42 @@ const (
var db *sql.DB 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) log.SetFlags(log.LstdFlags | log.Lshortfile)
conf, err := ReadConfig()
if err != nil {
log.Fatalln(err)
}
tpl, err := template.ParseGlob("templates/*.html") tpl, err := template.ParseGlob("templates/*.html")
if err != nil { if err != nil {
log.Fatalln(err) log.Fatalln(err)
} }
db, err = sql.Open("sqlite3", "calibre.db") db, err = sql.Open("sqlite3", conf.DbPath)
if err != nil { if err != nil {
log.Fatalln(err) log.Fatalln(err)
} }
@ -39,6 +75,7 @@ func init() {
} }
assets() assets()
router(app) router(app)
return conf
} }
func assets() { func assets() {
@ -55,6 +92,7 @@ func router(app *bouquins.Bouquins) {
} }
func main() { func main() {
conf := initApp()
defer db.Close() defer db.Close()
http.ListenAndServe(":9000", nil) http.ListenAndServe(conf.BindAddress, nil)
} }