~evanj/evanjon.es

evanjon.es/main.go -rw-r--r-- 7.5 KiB
fecbd67cEvan J Feat(*): Redesign. 8 months ago
                                                                                
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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
package main

import (
	"bytes"
	"context"
	"embed"
	"encoding/json"
	"errors"
	"fmt"
	"html/template"
	"io"
	"io/ioutil"
	"log"
	"net/http"
	"net/url"
	"os"

	"golang.org/x/sync/errgroup"
)

// TODO:
// 	cache
// 	rss
// 	verify html
// 	made with bsd and vi
// 	async GetContent
// 	author

var (
	//go:embed main.go go.mod go.sum makefile static/*
	sourceCode embed.FS

	//go:embed static/*
	staticFS embed.FS
	static   = template.Must(template.New("").
			ParseFS(staticFS, "static/css/*", "static/html/*"))

	addr = os.Getenv("ADDR")
	user = os.Getenv("WP_USER")
	pass = os.Getenv("WP_PASS")
	home = os.Getenv("WP_HOME")

	// staticBlogHTML    = static.Lookup("blog.tmpl")
	staticErrHTML     = static.Lookup("err.tmpl")
	staticContentHTML = static.Lookup("content.tmpl")

	ErrNotFound = errors.New("failed to find content")
)

// DATA

type Menu struct {
	Items []struct {
		Title, URL string
	}
}

type Content struct {
	Date     string
	Modified string
	Slug     string
	Type     string
	Title    struct{ Rendered template.HTML }
	Content  struct{ Rendered template.HTML }
	Excerpt  struct{ Rendered template.HTML }
}

type Media struct {
	URL string `json:"source_url"`
}

// SERVICES

type WP struct {
	url, user, pass, homeSlug string
	client                    *http.Client
}

func NewWP(url, user, pass, home string) WP {
	return WP{url, user, pass, home, http.DefaultClient}
}

func (wp WP) request(ctx context.Context, url string) (*http.Response, error) {
	req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
	if err != nil {
		return nil, err
	}
	req.SetBasicAuth(wp.user, wp.pass)
	return wp.client.Do(req)
}

func (wp WP) get(ctx context.Context, path string, data interface{}) error {
	resp, err := wp.request(ctx, fmt.Sprintf("%s%s", wp.url, path))
	if err != nil {
		return err
	}
	defer resp.Body.Close()
	bytes, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return err
	}
	return json.Unmarshal(bytes, data)
}

func (wp WP) GetMenu(ctx context.Context) (m Menu, err error) {
	err = wp.get(ctx, "/wp-json/menus/v1/menus/main-nav", &m)
	return
}

func (wp WP) FetchMedia(ctx context.Context, m Media) (*http.Response, error) {
	return wp.request(ctx, m.URL)
}

func (wp WP) FetchRSS(ctx context.Context) (*http.Response, error) {
	return wp.request(ctx, fmt.Sprintf("%s%s", wp.url, "/feed"))
}

func (wp WP) GetPostList(ctx context.Context) (l []Content, err error) {
	// TODO: Paged response.
	err = wp.get(ctx, "/wp-json/wp/v2/posts", &l)
	return
}

func (wp WP) GetMedia(ctx context.Context, slug string) (Media, error) {
	var (
		list []Media
		q    = url.Values{"search": []string{slug}}
		err  = wp.get(ctx, "/wp-json/wp/v2/media?"+q.Encode(), &list)
	)
	if err != nil {
		return Media{}, err
	}
	if len(list) < 1 {
		return Media{}, ErrNotFound
	}
	return list[0], err
}

//go:generate sh -c "cat errgrouprace.tmpl | sed 's/T/Content/g' > errgroupsrace.generated.go"

func (wp WP) GetContent(ctx context.Context, slug string) (Content, error) {
	r := NewRaceContent(ctx)
	r.Go(func() (Content, error) {
		return wp.getPage(ctx, slug)
	})
	r.Go(func() (Content, error) {
		return wp.getPost(ctx, slug)
	})
	return r.Wait()
}

func (wp WP) GetHome(ctx context.Context) (Content, error) {
	return wp.GetContent(ctx, wp.homeSlug)
}

func (wp WP) getPage(ctx context.Context, slug string) (Content, error) {
	var (
		list []Content
		q    = url.Values{"slug": []string{slug}}
		err  = wp.get(ctx, "/wp-json/wp/v2/pages?"+q.Encode(), &list)
	)
	if err != nil {
		return Content{}, err
	}
	if len(list) < 1 {
		return Content{}, ErrNotFound
	}
	return list[0], err
}

func (wp WP) getPost(ctx context.Context, slug string) (Content, error) {
	var (
		list []Content
		q    = url.Values{"slug": []string{slug}}
		err  = wp.get(ctx, "/wp-json/wp/v2/posts?"+q.Encode(), &list)
	)
	if err != nil {
		return Content{}, err
	}
	if len(list) < 1 {
		return Content{}, ErrNotFound
	}
	return list[0], err
}

// CONTROLLERS

type Controller struct {
	log *log.Logger
	wp  WP
}

func NewController(log *log.Logger, wp WP) Controller {
	return Controller{log: log, wp: wp}
}

func (c Controller) String(w http.ResponseWriter, r *http.Request, sc int, out string) {
	w.WriteHeader(sc)
	w.Write([]byte(out))
}

func (c Controller) Err(w http.ResponseWriter, r *http.Request, sc int, err error) {
	c.HTML(w, r, http.StatusOK, staticErrHTML, err)
}

func (c Controller) HTML(w http.ResponseWriter, r *http.Request, sc int, tmpl *template.Template, data interface{}) {
	if tmpl == nil {
		c.log.Println("not a valid template")
		c.String(w, r, http.StatusInternalServerError, "failed to create HTML response: developer error")
		return
	}

	buffer := bytes.Buffer{}
	err := tmpl.Execute(&buffer, data)
	if err != nil {
		c.log.Println(err)
		c.String(w, r, http.StatusInternalServerError, "failed to create HTML response: unexpected error")
		return
	}

	w.WriteHeader(sc)
	w.Write(buffer.Bytes())
}

type ContentController struct {
	Controller
}

func NewContentController(c Controller) ContentController {
	return ContentController{c}
}

func (c ContentController) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	switch r.URL.Path {
	case "/posts":
		fallthrough
	case "/blog":
		http.Redirect(w, r, "/#blog", http.StatusPermanentRedirect)

	default:
		var (
			menu    Menu
			content Content
			list    []Content
			eg      errgroup.Group
			isHome  = r.URL.Path == "/"
			slug    = r.URL.Path[1:]
		)

		eg.Go(func() error {
			if isHome {
				c, err := c.wp.GetHome(r.Context())
				if err == nil {
					content = c
				}
				return err
			}
			c, err := c.wp.GetContent(r.Context(), slug)
			if err == nil {
				content = c
			}
			return err

		})

		eg.Go(func() error {
			m, err := c.wp.GetMenu(r.Context())
			if err == nil {
				menu = m
			}
			return err
		})

		if isHome {
			eg.Go(func() error {
				l, err := c.wp.GetPostList(r.Context())
				if err == nil {
					list = l
				}
				return err
			})
		}

		if err := eg.Wait(); err != nil {
			c.Err(w, r, http.StatusInternalServerError, err)
			return
		}

		c.HTML(w, r, http.StatusOK, staticContentHTML, map[string]interface{}{
			"Content": content,
			"List":    list,
			"Menu":    menu,
		})
	}
}

type MediaController struct {
	Controller
}

func NewMediaController(c Controller) MediaController {
	return MediaController{c}
}

func (c MediaController) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	if len(r.URL.Path) < 2 {
		c.Err(w, r, http.StatusBadRequest, ErrNotFound) // TODO: Better error message?
		return
	}

	media, err := c.wp.GetMedia(r.Context(), r.URL.Path[1:])
	if err != nil {
		c.Err(w, r, http.StatusInternalServerError, err)
		return
	}

	resp, err := c.wp.FetchMedia(r.Context(), media)
	if err != nil {
		c.Err(w, r, http.StatusInternalServerError, err)
		return
	}
	defer resp.Body.Close()

	w.Header().Add("cache-control", "public, max-age=86400")
	w.Header().Add("content-type", resp.Header.Get("content-type"))
	if _, err := io.Copy(w, resp.Body); err != nil {
		c.Err(w, r, http.StatusInternalServerError, err)
		return
	}
}

func main() {
	var (
		out = os.Stdout
		l   = log.New(out, "[evanjon.es]: ", 0)
		wp  = NewWP("https://wp.evanjon.es", user, pass, home)
		cc  = NewContentController(NewController(log.New(out, "[evanjon.es:ContentContoller]: ", 0), wp))
		mc  = NewMediaController(NewController(log.New(out, "[evanjon.es:MediaContoller]: ", 0), wp))
	)

	http.Handle("/", cc)
	http.Handle("/media/", http.StripPrefix("/media/", mc))
	http.Handle("/source/", http.StripPrefix("/source/", http.FileServer(http.FS(sourceCode))))

	l.Println("listening on", addr)
	if err := http.ListenAndServe(addr, nil); err != nil {
		l.Fatal(err)
	}
}