/
handle_article.go
100 lines (91 loc) · 1.97 KB
/
handle_article.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
package handler
import (
"github.com/arussellsaw/news/dao"
"github.com/arussellsaw/news/domain"
"github.com/monzo/slog"
"html/template"
"net/http"
"sort"
"strings"
)
func handleArticle(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
t := template.New("frame.html")
t, err := t.ParseFiles("tmpl/frame.html", "tmpl/meta.html", "tmpl/article.html")
if err != nil {
slog.Error(ctx, "Error parsing template: %s", err)
http.Error(w, err.Error(), 500)
return
}
article, err := dao.GetArticle(ctx, r.URL.Query().Get("id"))
if err != nil {
http.Error(w, err.Error(), 500)
return
}
u := domain.UserFromContext(ctx)
var sources []domain.Source
if u != nil {
sources, err = dao.GetSources(ctx, u.ID)
if err != nil {
http.Error(w, err.Error(), 500)
return
}
} else {
sources = domain.GetSources()
}
for _, src := range sources {
if src.FeedURL == article.Source.FeedURL {
article.Source = src
}
}
a := articlePage{
Article: article,
base: base{
User: domain.UserFromContext(ctx),
Meta: Meta{
Title: article.Title + " - " + article.Source.Name,
Description: preview(article.Content),
Image: article.ImageURL,
URL: r.URL.String(),
},
},
}
byFeedURL := make(map[string]domain.Source)
smap := make(map[string]struct{})
for _, s := range sources {
byFeedURL[s.FeedURL] = s
for _, cat := range s.Categories {
smap[cat] = struct{}{}
}
}
for cat := range smap {
a.Categories = append(a.Categories, cat)
}
sort.Strings(a.Categories)
err = t.Execute(w, a)
if err != nil {
slog.Error(ctx, "Error executing template: %s", err)
http.Error(w, err.Error(), 500)
return
}
}
type articlePage struct {
Article *domain.Article
base
}
func preview(es []domain.Element) string {
var out string
for _, e := range es {
if e.Type != "text" {
continue
}
if strings.TrimSpace(e.Value) == "" {
continue
}
out += e.Value
}
if len(out) <= 400 {
return out
}
return out[:400]
}