generated from wesen/wesen-go-template
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathhandlers.go
101 lines (84 loc) · 2.22 KB
/
handlers.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
93
94
95
96
97
98
99
100
101
package server
import (
_ "embed"
"html/template"
"net/http"
"strings"
"github.com/go-go-golems/prompto/pkg"
)
//go:embed static/js/favorites.js
var favoritesJS string
//go:embed static/templates/root.html
var rootTemplate string
//go:embed static/templates/repoList.html
var repoListTemplate string
func rootHandler(state *ServerState) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
http.NotFound(w, r)
return
}
tmpl, err := state.CreateTemplateWithFuncs("root", rootTemplate+repoListTemplate)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
data := struct {
Groups []string
FavoritesJS template.JS
}{
Groups: state.GetAllGroups(),
FavoritesJS: template.JS(favoritesJS),
}
w.Header().Set("Content-Type", "text/html")
err = tmpl.Execute(w, data)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
}
func searchHandler(state *ServerState) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
query := r.FormValue("search")
results := make(map[string][]pkg.Prompto)
state.mu.RLock()
for _, file := range state.GetAllPromptos() {
if strings.Contains(strings.ToLower(file.Name), strings.ToLower(query)) {
group := strings.SplitN(file.Name, "/", 2)[0]
results[group] = append(results[group], file)
}
}
state.mu.RUnlock()
groups := make([]string, 0)
for group := range results {
groups = append(groups, group)
}
funcMap := template.FuncMap{
"PromptosByGroup": func(group string) []pkg.Prompto {
return results[group]
},
}
tmpl, err := state.CreateTemplateWithFuncs("repoList", repoListTemplate)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
tmpl = tmpl.Funcs(funcMap)
data := struct {
Groups []string
}{
Groups: groups,
}
w.Header().Set("Content-Type", "text/html")
err = tmpl.ExecuteTemplate(w, "repoList", data)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
}