dorfylegends/backend/server/resource.go

73 lines
1.7 KiB
Go
Raw Normal View History

2022-04-09 19:37:44 +03:00
package server
import (
"fmt"
2022-04-26 18:39:24 +03:00
"io/fs"
2022-04-09 19:37:44 +03:00
"net/http"
"strconv"
"github.com/gorilla/mux"
2022-04-26 18:39:24 +03:00
"github.com/robertjanetzko/LegendsBrowser2/backend/model"
"github.com/robertjanetzko/LegendsBrowser2/backend/templates"
2022-04-09 19:37:44 +03:00
)
2022-04-26 10:24:16 +03:00
type Parms map[string]string
2022-04-09 19:37:44 +03:00
2022-04-26 18:39:24 +03:00
// func (srv *DfServer) RegisterPage(path string, template string, accessor func(Parms) any) {
// get := func(w http.ResponseWriter, r *http.Request) {
// err := srv.templates.Render(w, template, accessor(mux.Vars(r)))
// if err != nil {
// fmt.Fprintln(w, err)
// fmt.Println(err)
// }
// }
// srv.router.HandleFunc(path, get).Methods("GET")
// }
func (srv *DfServer) RegisterWorldPage(path string, template string, accessor func(Parms) any) {
2022-04-09 19:37:44 +03:00
get := func(w http.ResponseWriter, r *http.Request) {
2022-04-26 18:39:24 +03:00
if srv.context.world == nil {
srv.renderLoading(w, r)
return
}
td := &templates.TemplateData{
Context: &model.Context{World: srv.context.world},
Data: accessor(mux.Vars(r)),
}
err := srv.templates.Render(w, template, td)
2022-04-09 19:37:44 +03:00
if err != nil {
2022-04-26 10:24:16 +03:00
fmt.Fprintln(w, err)
2022-04-09 19:37:44 +03:00
fmt.Println(err)
}
}
2022-04-26 10:24:16 +03:00
srv.router.HandleFunc(path, get).Methods("GET")
}
2022-04-26 18:39:24 +03:00
func (srv *DfServer) RegisterWorldResourcePage(path string, template string, accessor func(int) any) {
srv.RegisterWorldPage(path, template, func(params Parms) any {
2022-04-26 10:24:16 +03:00
id, _ := strconv.Atoi(params["id"])
return accessor(id)
})
2022-04-09 19:37:44 +03:00
}
2022-04-26 18:39:24 +03:00
type paths struct {
Current string
List []fs.FileInfo
}
func (srv *DfServer) renderLoading(w http.ResponseWriter, r *http.Request) {
if srv.context.isLoading {
err := srv.templates.Render(w, "loading.html", nil)
if err != nil {
fmt.Fprintln(w, err)
fmt.Println(err)
}
} else {
http.Redirect(w, r, "/load", http.StatusSeeOther)
}
}