/
taxonomies.go
65 lines (60 loc) · 1.65 KB
/
taxonomies.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
package main
import (
"context"
"database/sql"
"errors"
"fmt"
"net/http"
"github.com/go-chi/chi/v5"
)
const taxonomyContextKey = "taxonomy"
func (a *goBlog) serveTaxonomy(w http.ResponseWriter, r *http.Request) {
blog, _ := a.getBlog(r)
tax := r.Context().Value(taxonomyContextKey).(*configTaxonomy)
allValues, err := a.db.allTaxonomyValues(blog, tax.Name)
if err != nil {
a.serveError(w, r, err.Error(), http.StatusInternalServerError)
return
}
a.render(w, r, a.renderTaxonomy, &renderData{
Canonical: a.getFullAddress(r.URL.Path),
Data: &taxonomyRenderData{
taxonomy: tax,
valueGroups: groupStrings(allValues),
},
})
}
func (a *goBlog) serveTaxonomyValue(w http.ResponseWriter, r *http.Request) {
_, bc := a.getBlog(r)
tax := r.Context().Value(taxonomyContextKey).(*configTaxonomy)
taxValueParam := chi.URLParam(r, "taxValue")
if taxValueParam == "" {
a.serve404(w, r)
return
}
// Get value from DB
row, err := a.db.QueryRow(
"select value from post_parameters where parameter = @tax and urlize(value) = @taxValue limit 1",
sql.Named("tax", tax.Name), sql.Named("taxValue", taxValueParam),
)
if err != nil {
a.serveError(w, r, err.Error(), http.StatusInternalServerError)
return
}
var taxValue string
err = row.Scan(&taxValue)
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
a.serve404(w, r)
return
}
a.serveError(w, r, err.Error(), http.StatusInternalServerError)
return
}
// Serve index
a.serveIndex(w, r.WithContext(context.WithValue(r.Context(), indexConfigKey, &indexConfig{
path: bc.getRelativePath(fmt.Sprintf("/%s/%s", tax.Name, taxValueParam)),
tax: tax,
taxValue: taxValue,
})))
}