-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
92 lines (79 loc) · 1.76 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package main
import (
"embed"
"encoding/json"
"net/http"
"os"
"sort"
"strings"
"text/template"
)
var (
port = os.Getenv("PORT")
githubToken = os.Getenv("GITHUB_TOKEN")
//go:embed static/*
pages embed.FS
// recipe indexes
titleIndex = map[string]recipe{}
ingredientIndex = map[string][]recipe{}
)
type recipe struct {
URL string
Category string
Picture string
Title string
Language string
Servings string
Time string
Author string
Source string
Ingredients []string
Instructions []string
Visits int
Notes []string
}
var pageTemplate *template.Template
var recipes []recipe
func main() {
if port == "" {
port = "8080"
}
var err error
pageTemplate, err = template.ParseFS(pages, "static/*.*")
if err != nil {
panic("parse templates: " + err.Error())
}
// parse recipes
db, err := os.Open("db.json")
if err != nil {
panic("open recipes: " + err.Error())
}
err = json.NewDecoder(db).Decode(&recipes)
if err != nil {
panic("decode recipes: " + err.Error())
}
db.Close()
// build indexes
go func() {
for _, r := range recipes {
titleIndex[r.Title] = r
ingreds := map[string]struct{}{}
for _, ingred := range r.Ingredients {
ings := strings.Fields(ingred)
for _, i := range ings {
ingreds[strings.ToLower(i)] = struct{}{}
}
}
for i := range ingreds {
ingredientIndex[i] = append(ingredientIndex[i], r)
}
}
sort.Slice(recipes, func(i, j int) bool { return recipes[i].Visits > recipes[j].Visits })
}()
// For compatibility
http.HandleFunc("/images/", imageHandler)
http.HandleFunc("/api", apiHandler)
http.HandleFunc("/upload.html", uploadHandler)
http.HandleFunc("/", staticHandler)
http.ListenAndServe(":"+port, nil)
}