From abdc63bfda42e60540d206a5fd5be28341e46617 Mon Sep 17 00:00:00 2001 From: Pancakes Date: Tue, 23 Jul 2024 07:25:03 -0400 Subject: [PATCH] Use html/template for page generation --- ingame/browser/browser.go | 97 +++++++++++++------------------------- ingame/browser/template.go | 48 +++++++++++++++++++ 2 files changed, 81 insertions(+), 64 deletions(-) create mode 100644 ingame/browser/template.go diff --git a/ingame/browser/browser.go b/ingame/browser/browser.go index 0d3f428..d232e23 100644 --- a/ingame/browser/browser.go +++ b/ingame/browser/browser.go @@ -20,40 +20,35 @@ package browser import ( "fmt" + "html/template" "net/http" "reboxed/db" "reboxed/utils" "strconv" ) -var categories = map[string]string{ - "entities": "entity", - "weapons": "weapon", - "props": "prop", - "saves": "savemap", - "maps": "map", +type BrowserTemplateData struct { + InGame bool + Category string + PageNum int + Packages []utils.Package + PrevLink string + NextLink string } -const header = ` -reboxed - -` - const itemsPerPage = 50 +var ( + categories = map[string]string{ + "entities": "entity", + "weapons": "weapon", + "props": "prop", + "saves": "savemap", + "maps": "map", + } + t, _ = template.New("Browser").Parse(tmpl) +) + func Handle(w http.ResponseWriter, r *http.Request) { var category string category, ok := categories[r.PathValue("category")] @@ -62,20 +57,6 @@ func Handle(w http.ResponseWriter, r *http.Request) { return } - body := header - - body += `
` - page, _ := strconv.Atoi(r.URL.Query().Get("page")) if page < 1 { page = 1 @@ -87,28 +68,9 @@ func Handle(w http.ResponseWriter, r *http.Request) { return } - for _, pkg := range list { - action := "spawn" - if category == "map" { - action = "install" - } - - if category == "savemap" { - if r.Header.Get("MAP") != "" && r.Header.Get("MAP") != pkg.Dataname { - continue - } - } - - link := fmt.Sprintf(`href="garrysmod://%s/%s/%d/%d"`, action, category, pkg.ID, pkg.Revision) - - body += fmt.Sprintf(``, link, pkg.ID, pkg.Name) - } - - body += "
" - - previous := fmt.Sprintf("?page=%d", page-1) + prev := fmt.Sprintf("?page=%d", page-1) if page <= 1 { - previous = "#" + prev = "#" } next := fmt.Sprintf("?page=%d", page+1) @@ -116,9 +78,16 @@ func Handle(w http.ResponseWriter, r *http.Request) { next = "#" } - body += fmt.Sprintf(``, previous, page, next) - - body += "" - - w.Write([]byte(body)) + err = t.Execute(w, BrowserTemplateData{ + InGame: r.Header.Get("GMOD_VERSION") != "", + Category: category, + PageNum: page, + Packages: list, + PrevLink: prev, + NextLink: next, + }) + if err != nil { + utils.WriteError(w, r, fmt.Sprintf("failed to execute template: %s", err)) + return + } } diff --git a/ingame/browser/template.go b/ingame/browser/template.go new file mode 100644 index 0000000..f88c9aa --- /dev/null +++ b/ingame/browser/template.go @@ -0,0 +1,48 @@ +package browser + +const tmpl = ` + + reboxed + + + + +
+ {{range .Packages}} + + {{end}} +
+ + +` \ No newline at end of file