summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorxengineering <me@xengineering.eu>2023-04-22 18:41:18 +0200
committerxengineering <me@xengineering.eu>2023-04-22 19:17:04 +0200
commita0cc83b88357e73a6bcae156b26029fc5257ac20 (patch)
tree3918f37fc5aebc058baf4ea201a98c4f0266cdf5
parenta13564a8f09ff0948a4dbbd434b7e1700164cdb4 (diff)
downloadceres-a0cc83b88357e73a6bcae156b26029fc5257ac20.tar
ceres-a0cc83b88357e73a6bcae156b26029fc5257ac20.tar.zst
ceres-a0cc83b88357e73a6bcae156b26029fc5257ac20.zip
Implement index page with JSON
-rw-r--r--handler.go31
-rw-r--r--recipe.go54
2 files changed, 57 insertions, 28 deletions
diff --git a/handler.go b/handler.go
index 04c4581..8a514e7 100644
--- a/handler.go
+++ b/handler.go
@@ -7,6 +7,7 @@ import (
"os"
"path/filepath"
"regexp"
+ "sort"
"strconv"
)
@@ -22,35 +23,11 @@ type Recipe struct {
}
func indexGet(w http.ResponseWriter, r *http.Request) {
+ list := getRecipeList()
- recipes := make([]Recipe, 0)
-
- entries, err := os.ReadDir(filepath.Join(config.Data, "recipes"))
- if err == nil {
- for _, v := range entries {
- if v.IsDir() == false {
- continue
- }
-
- _, err = strconv.Atoi(v.Name())
- if err != nil {
- continue
- }
-
- textpath := filepath.Join(config.Data, "recipes", v.Name(), "text")
- data, _ := ioutil.ReadFile(textpath)
- markup := Markup(data)
-
- recipes = append(recipes, Recipe{
- v.Name(),
- markup.title(),
- string(data),
- "",
- })
- }
- }
+ sort.Sort(list)
- ServeTemplate(w, "index.html", recipes)
+ ServeTemplate(w, "index.html", list)
}
func recipeGet(w http.ResponseWriter, r *http.Request) {
diff --git a/recipe.go b/recipe.go
index 167f690..76c5204 100644
--- a/recipe.go
+++ b/recipe.go
@@ -2,8 +2,11 @@ package main
import (
"encoding/json"
- "path/filepath"
"io/ioutil"
+ "log"
+ "os"
+ "path/filepath"
+ "strconv"
)
type recipe struct {
@@ -35,3 +38,52 @@ func getRecipe(id string) (recipe, error) {
return r, nil
}
+
+type recipeList []struct {
+ Id string
+ Title string
+}
+
+func (a recipeList) Len() int { return len(a) }
+func (a recipeList) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
+func (a recipeList) Less(i, j int) bool { return a[i].Title < a[j].Title }
+
+func getRecipeList() recipeList {
+ recipes := make(recipeList, 0)
+
+ path := filepath.Join(config.Data, "recipes")
+ entries, err := os.ReadDir(path)
+ if err == nil {
+ for _, v := range entries {
+ if v.IsDir() == false {
+ continue
+ }
+
+ _, err = strconv.Atoi(v.Name())
+ if err != nil {
+ continue
+ }
+
+ textpath := filepath.Join(config.Data, "recipes", v.Name(), "text")
+ data, err := ioutil.ReadFile(textpath)
+ if err != nil {
+ continue
+ }
+
+ r := recipe{}
+ err = json.Unmarshal(data, &r)
+ if err != nil {
+ continue
+ }
+
+ recipes = append(recipes, struct {
+ Id string
+ Title string
+ }{v.Name(), r.Title})
+ }
+ } else {
+ log.Printf("Could not read directory '%s'\n", path)
+ }
+
+ return recipes
+}