99 lines
1.8 KiB
Go
99 lines
1.8 KiB
Go
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/"
|
|
JS = "/js/"
|
|
CSS = "/css/"
|
|
FONTS = "/fonts/"
|
|
)
|
|
|
|
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.Bouquins{
|
|
tpl,
|
|
db,
|
|
}
|
|
assets()
|
|
router(app)
|
|
return conf
|
|
}
|
|
|
|
func assets() {
|
|
http.Handle(JS, http.FileServer(http.Dir("assets")))
|
|
http.Handle(CSS, http.FileServer(http.Dir("assets")))
|
|
http.Handle(FONTS, http.FileServer(http.Dir("assets")))
|
|
}
|
|
|
|
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() {
|
|
conf := initApp()
|
|
defer db.Close()
|
|
http.ListenAndServe(conf.BindAddress, nil)
|
|
}
|