go-bouquins/main.go

99 lines
1.8 KiB
Go
Raw Normal View History

2017-07-30 14:06:38 +00:00
package main
import (
2017-07-30 18:14:20 +00:00
"database/sql"
2017-08-01 13:37:58 +00:00
"encoding/json"
2017-07-30 15:20:48 +00:00
"html/template"
"log"
2017-07-30 14:06:38 +00:00
"net/http"
2017-08-01 13:37:58 +00:00
"os"
2017-07-30 14:06:38 +00:00
2017-07-31 17:37:52 +00:00
_ "github.com/mattn/go-sqlite3"
2017-07-30 14:06:38 +00:00
"meutel.net/meutel/go-bouquins/bouquins"
)
2017-08-01 13:37:58 +00:00
type BouquinsConf struct {
BindAddress string `json:"bind-address"`
DbPath string `json:"db-path"`
}
2017-07-30 14:06:38 +00:00
const (
INDEX = "/"
2017-08-01 13:37:58 +00:00
BOOKS = "/books/"
AUTHORS = "/authors/"
SERIES = "/series/"
2017-07-30 14:06:38 +00:00
JS = "/js/"
CSS = "/css/"
2017-07-30 16:09:27 +00:00
FONTS = "/fonts/"
2017-07-30 14:06:38 +00:00
)
2017-07-30 18:14:20 +00:00
var db *sql.DB
2017-08-01 13:37:58 +00:00
// 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 {
2017-07-31 17:37:52 +00:00
log.SetFlags(log.LstdFlags | log.Lshortfile)
2017-08-01 13:37:58 +00:00
conf, err := ReadConfig()
if err != nil {
log.Fatalln(err)
}
2017-07-30 15:20:48 +00:00
tpl, err := template.ParseGlob("templates/*.html")
if err != nil {
log.Fatalln(err)
}
2017-08-01 13:37:58 +00:00
db, err = sql.Open("sqlite3", conf.DbPath)
2017-07-30 18:14:20 +00:00
if err != nil {
log.Fatalln(err)
}
2017-07-30 15:20:48 +00:00
app := &bouquins.Bouquins{
tpl,
2017-07-30 18:14:20 +00:00
db,
2017-07-30 15:20:48 +00:00
}
2017-07-30 14:06:38 +00:00
assets()
router(app)
2017-08-01 13:37:58 +00:00
return conf
2017-07-30 14:06:38 +00:00
}
func assets() {
http.Handle(JS, http.FileServer(http.Dir("assets")))
http.Handle(CSS, http.FileServer(http.Dir("assets")))
2017-07-30 16:09:27 +00:00
http.Handle(FONTS, http.FileServer(http.Dir("assets")))
2017-07-30 14:06:38 +00:00
}
func router(app *bouquins.Bouquins) {
http.HandleFunc(INDEX, app.IndexPage)
http.HandleFunc(BOOKS, app.BooksPage)
http.HandleFunc(AUTHORS, app.AuthorsPage)
http.HandleFunc(SERIES, app.SeriesPage)
}
func main() {
2017-08-01 13:37:58 +00:00
conf := initApp()
2017-07-30 18:14:20 +00:00
defer db.Close()
2017-08-01 13:37:58 +00:00
http.ListenAndServe(conf.BindAddress, nil)
2017-07-30 14:06:38 +00:00
}