dorfylegends/backend/server/resource.go

48 lines
1001 B
Go
Raw Permalink Normal View History

2022-04-09 19:37:44 +03:00
package server
import (
"fmt"
"net/http"
2022-04-30 10:45:31 +03:00
"reflect"
2022-04-09 19:37:44 +03:00
"strconv"
"github.com/gorilla/mux"
)
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) 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
}
2022-05-05 23:18:31 +03:00
params := mux.Vars(r)
for k, v := range r.URL.Query() {
params[k] = v[0]
}
data := accessor(params)
2022-04-30 14:35:56 +03:00
if data == nil || (reflect.ValueOf(data).Kind() == reflect.Ptr && reflect.ValueOf(data).IsNil()) {
2022-04-30 10:45:31 +03:00
srv.notFound(w)
return
}
err := srv.templates.Render(w, template, data)
2022-04-09 19:37:44 +03:00
if err != nil {
2022-05-03 15:59:47 +03:00
fmt.Fprint(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
}