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"` } var db *sql.DB // 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", conf.DbPath) if err != nil { log.Fatalln(err) } app := &Bouquins{ tpl, db, } err = app.PrepareAll() if err != nil { log.Fatalln(err) } assets() router(app) return conf } func assets() { http.Handle(URL_JS, http.FileServer(http.Dir("assets"))) http.Handle(URL_CSS, http.FileServer(http.Dir("assets"))) http.Handle(URL_FONTS, http.FileServer(http.Dir("assets"))) } func router(app *Bouquins) { http.HandleFunc(URL_INDEX, app.IndexPage) http.HandleFunc(URL_BOOKS, app.BooksPage) http.HandleFunc(URL_AUTHORS, app.AuthorsPage) http.HandleFunc(URL_SERIES, app.SeriesPage) } func main() { conf := initApp() defer db.Close() http.ListenAndServe(conf.BindAddress, nil) }