Refactor router initialization into constructor

This commit is contained in:
bronku 2025-03-22 08:57:19 +01:00
parent 4830fbc870
commit 08d41b0348
3 changed files with 25 additions and 15 deletions

View file

@ -28,6 +28,7 @@
## Security
- [x] Authentication System
- [ ] Persistant logins accross server restarts
- [x] User login
- [ ] User logout
- [ ] Role-based access (admin, staff)

18
main.go
View file

@ -10,21 +10,13 @@ import (
)
func main() {
var err error
var h router.Router
var a auth.Authenticator
h, err := router.New()
if err != nil {
log.Fatal(err)
}
defer h.Close()
err = h.LoadTemplates()
if err != nil {
log.Fatal("can't parse templates: ", err)
}
err = h.OenStore()
if err != nil {
log.Fatal("can't open the databse", err)
}
var a auth.Authenticator
a = auth.New()
// #todo: make handler functions private, and create a servemux in router

View file

@ -22,19 +22,36 @@ func (h *Router) Close() {
}
}
func (h *Router) OenStore() error {
func (h *Router) openStore() error {
var err error
h.s, err = store.OpenStore("./foo.db")
if err != nil {
h.s.Close()
}
return err
}
// #todo embed templates, and load them in init function
func (h *Router) LoadTemplates() error {
func (h *Router) loadTemplates() error {
var err error
h.tmpl, err = template.ParseFiles("index.html", "order.html")
return err
}
func New() (*Router, error) {
var router Router
var err error
err = router.loadTemplates()
if err != nil {
return nil, err
}
err = router.openStore()
if err != nil {
return nil, err
}
return &router, nil
}
func (h *Router) Form(w http.ResponseWriter, r *http.Request) {
url := strings.Split(r.URL.String(), "/")
o := store.Order{