You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
422 lines
9.1 KiB
422 lines
9.1 KiB
2 years ago
|
package http
|
||
2 years ago
|
|
||
|
import (
|
||
2 years ago
|
"bytes"
|
||
2 years ago
|
"context"
|
||
2 years ago
|
"errors"
|
||
|
"fmt"
|
||
|
"html/template"
|
||
|
"net/http"
|
||
|
"path/filepath"
|
||
|
"strings"
|
||
2 years ago
|
txttpl "text/template"
|
||
2 years ago
|
"time"
|
||
2 years ago
|
|
||
|
"github.com/gomarkdown/markdown"
|
||
|
"github.com/gomarkdown/markdown/html"
|
||
|
"github.com/gomarkdown/markdown/parser"
|
||
2 years ago
|
"github.com/mediocregopher/blog.mediocregopher.com/srv/http/apiutil"
|
||
2 years ago
|
"github.com/mediocregopher/blog.mediocregopher.com/srv/post"
|
||
2 years ago
|
"github.com/mediocregopher/mediocre-go-lib/v2/mctx"
|
||
2 years ago
|
)
|
||
|
|
||
2 years ago
|
func (a *api) parsePostBody(post post.Post) (*txttpl.Template, error) {
|
||
2 years ago
|
tpl := txttpl.New("root")
|
||
|
tpl = tpl.Funcs(txttpl.FuncMap(a.tplFuncs()))
|
||
|
|
||
|
tpl = txttpl.Must(tpl.New("image.html").Parse(mustReadTplFile("image.html")))
|
||
|
tpl = tpl.Funcs(txttpl.FuncMap{
|
||
|
"Image": func(id string) (string, error) {
|
||
|
|
||
|
tplPayload := struct {
|
||
|
ID string
|
||
|
Resizable bool
|
||
|
}{
|
||
|
ID: id,
|
||
|
Resizable: isImgResizable(id),
|
||
|
}
|
||
|
|
||
|
buf := new(bytes.Buffer)
|
||
|
if err := tpl.ExecuteTemplate(buf, "image.html", tplPayload); err != nil {
|
||
|
return "", err
|
||
|
}
|
||
|
|
||
|
return buf.String(), nil
|
||
|
},
|
||
|
})
|
||
|
|
||
2 years ago
|
tpl, err := tpl.New(post.ID + "-body.html").Parse(post.Body)
|
||
2 years ago
|
|
||
|
if err != nil {
|
||
|
return nil, err
|
||
|
}
|
||
|
|
||
|
return tpl, nil
|
||
|
}
|
||
|
|
||
2 years ago
|
type postTplPayload struct {
|
||
|
post.StoredPost
|
||
|
SeriesPrevious, SeriesNext *post.StoredPost
|
||
|
Body template.HTML
|
||
|
}
|
||
|
|
||
|
func (a *api) postToPostTplPayload(storedPost post.StoredPost) (postTplPayload, error) {
|
||
2 years ago
|
|
||
2 years ago
|
bodyTpl, err := a.parsePostBody(storedPost.Post)
|
||
2 years ago
|
if err != nil {
|
||
|
return postTplPayload{}, fmt.Errorf("parsing post body as template: %w", err)
|
||
|
}
|
||
|
|
||
|
bodyBuf := new(bytes.Buffer)
|
||
2 years ago
|
|
||
2 years ago
|
if err := bodyTpl.Execute(bodyBuf, nil); err != nil {
|
||
|
return postTplPayload{}, fmt.Errorf("executing post body as template: %w", err)
|
||
|
}
|
||
|
|
||
2 years ago
|
// this helps the markdown renderer properly parse pages which end in a
|
||
|
// `</script>` tag... I don't know why.
|
||
|
_, _ = bodyBuf.WriteString("\n")
|
||
|
|
||
2 years ago
|
parserExt := parser.CommonExtensions | parser.AutoHeadingIDs
|
||
|
parser := parser.NewWithExtensions(parserExt)
|
||
|
|
||
2 years ago
|
htmlFlags := html.HrefTargetBlank
|
||
2 years ago
|
htmlRenderer := html.NewRenderer(html.RendererOptions{Flags: htmlFlags})
|
||
|
|
||
2 years ago
|
renderedBody := markdown.ToHTML(bodyBuf.Bytes(), parser, htmlRenderer)
|
||
2 years ago
|
|
||
|
tplPayload := postTplPayload{
|
||
|
StoredPost: storedPost,
|
||
|
Body: template.HTML(renderedBody),
|
||
|
}
|
||
|
|
||
|
if series := storedPost.Series; series != "" {
|
||
|
|
||
|
seriesPosts, err := a.params.PostStore.GetBySeries(series)
|
||
|
if err != nil {
|
||
|
return postTplPayload{}, fmt.Errorf(
|
||
|
"fetching posts for series %q: %w", series, err,
|
||
|
)
|
||
|
}
|
||
|
|
||
|
var foundThis bool
|
||
|
|
||
|
for i := range seriesPosts {
|
||
|
|
||
|
seriesPost := seriesPosts[i]
|
||
|
|
||
|
if seriesPost.ID == storedPost.ID {
|
||
|
foundThis = true
|
||
|
continue
|
||
|
}
|
||
|
|
||
|
if !foundThis {
|
||
2 years ago
|
tplPayload.SeriesNext = &seriesPost
|
||
2 years ago
|
continue
|
||
|
}
|
||
|
|
||
2 years ago
|
tplPayload.SeriesPrevious = &seriesPost
|
||
2 years ago
|
break
|
||
|
}
|
||
|
}
|
||
|
|
||
|
return tplPayload, nil
|
||
|
}
|
||
|
|
||
2 years ago
|
func (a *api) renderPostHandler() http.Handler {
|
||
|
|
||
|
tpl := a.mustParseBasedTpl("post.html")
|
||
2 years ago
|
renderPostsIndexHandler := a.renderPostsIndexHandler()
|
||
2 years ago
|
renderEditPostHandler := a.renderEditPostHandler(false)
|
||
2 years ago
|
|
||
|
return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
|
||
|
|
||
|
id := strings.TrimSuffix(filepath.Base(r.URL.Path), ".html")
|
||
|
|
||
2 years ago
|
if id == "/" {
|
||
2 years ago
|
renderPostsIndexHandler.ServeHTTP(rw, r)
|
||
|
return
|
||
|
}
|
||
|
|
||
|
if _, ok := r.URL.Query()["edit"]; ok {
|
||
|
renderEditPostHandler.ServeHTTP(rw, r)
|
||
2 years ago
|
return
|
||
|
}
|
||
|
|
||
2 years ago
|
storedPost, err := a.params.PostStore.GetByID(id)
|
||
|
|
||
|
if errors.Is(err, post.ErrPostNotFound) {
|
||
|
http.Error(rw, "Post not found", 404)
|
||
|
return
|
||
|
} else if err != nil {
|
||
|
apiutil.InternalServerError(
|
||
|
rw, r, fmt.Errorf("fetching post with id %q: %w", id, err),
|
||
|
)
|
||
|
return
|
||
|
}
|
||
|
|
||
2 years ago
|
tplPayload, err := a.postToPostTplPayload(storedPost)
|
||
2 years ago
|
|
||
2 years ago
|
if err != nil {
|
||
|
apiutil.InternalServerError(
|
||
|
rw, r, fmt.Errorf(
|
||
|
"generating template payload for post with id %q: %w",
|
||
|
id, err,
|
||
|
),
|
||
|
)
|
||
|
return
|
||
2 years ago
|
}
|
||
|
|
||
|
executeTemplate(rw, r, tpl, tplPayload)
|
||
|
})
|
||
|
}
|
||
|
|
||
2 years ago
|
func (a *api) renderPostsIndexHandler() http.Handler {
|
||
2 years ago
|
|
||
2 years ago
|
renderEditPostHandler := a.renderEditPostHandler(false)
|
||
2 years ago
|
tpl := a.mustParseBasedTpl("posts.html")
|
||
|
const pageCount = 20
|
||
2 years ago
|
|
||
|
return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
|
||
|
|
||
2 years ago
|
if _, ok := r.URL.Query()["edit"]; ok {
|
||
|
renderEditPostHandler.ServeHTTP(rw, r)
|
||
|
return
|
||
|
}
|
||
|
|
||
2 years ago
|
page, err := apiutil.StrToInt(r.FormValue("p"), 0)
|
||
|
if err != nil {
|
||
|
apiutil.BadRequest(
|
||
|
rw, r, fmt.Errorf("invalid page number: %w", err),
|
||
|
)
|
||
|
return
|
||
|
}
|
||
2 years ago
|
|
||
2 years ago
|
posts, hasMore, err := a.params.PostStore.Get(page, pageCount)
|
||
2 years ago
|
if err != nil {
|
||
|
apiutil.InternalServerError(
|
||
2 years ago
|
rw, r, fmt.Errorf("fetching page %d of posts: %w", page, err),
|
||
2 years ago
|
)
|
||
|
return
|
||
|
}
|
||
|
|
||
|
tplPayload := struct {
|
||
2 years ago
|
Posts []post.StoredPost
|
||
|
PrevPage, NextPage int
|
||
2 years ago
|
}{
|
||
2 years ago
|
Posts: posts,
|
||
|
PrevPage: -1,
|
||
|
NextPage: -1,
|
||
|
}
|
||
|
|
||
|
if page > 0 {
|
||
|
tplPayload.PrevPage = page - 1
|
||
|
}
|
||
|
|
||
|
if hasMore {
|
||
|
tplPayload.NextPage = page + 1
|
||
2 years ago
|
}
|
||
|
|
||
|
executeTemplate(rw, r, tpl, tplPayload)
|
||
|
})
|
||
|
}
|
||
2 years ago
|
|
||
2 years ago
|
func (a *api) renderEditPostHandler(isDraft bool) http.Handler {
|
||
2 years ago
|
|
||
|
tpl := a.mustParseBasedTpl("edit-post.html")
|
||
|
|
||
|
return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
|
||
|
|
||
|
id := filepath.Base(r.URL.Path)
|
||
|
|
||
|
var storedPost post.StoredPost
|
||
|
|
||
|
if id != "/" {
|
||
|
|
||
|
var err error
|
||
2 years ago
|
|
||
|
if isDraft {
|
||
|
storedPost.Post, err = a.params.PostDraftStore.GetByID(id)
|
||
|
} else {
|
||
|
storedPost, err = a.params.PostStore.GetByID(id)
|
||
|
}
|
||
2 years ago
|
|
||
|
if errors.Is(err, post.ErrPostNotFound) {
|
||
|
http.Error(rw, "Post not found", 404)
|
||
|
return
|
||
|
} else if err != nil {
|
||
|
apiutil.InternalServerError(
|
||
|
rw, r, fmt.Errorf("fetching post with id %q: %w", id, err),
|
||
|
)
|
||
|
return
|
||
|
}
|
||
2 years ago
|
|
||
|
} else if !isDraft {
|
||
|
http.Error(rw, "Post ID required in URL", 400)
|
||
|
return
|
||
2 years ago
|
}
|
||
|
|
||
2 years ago
|
tags, err := a.params.PostStore.GetTags()
|
||
|
if err != nil {
|
||
|
apiutil.InternalServerError(rw, r, fmt.Errorf("fetching tags: %w", err))
|
||
|
return
|
||
|
}
|
||
|
|
||
|
tplPayload := struct {
|
||
2 years ago
|
Post post.StoredPost
|
||
|
Tags []string
|
||
|
IsDraft bool
|
||
2 years ago
|
}{
|
||
2 years ago
|
Post: storedPost,
|
||
|
Tags: tags,
|
||
|
IsDraft: isDraft,
|
||
2 years ago
|
}
|
||
|
|
||
|
executeTemplate(rw, r, tpl, tplPayload)
|
||
2 years ago
|
})
|
||
|
}
|
||
|
|
||
2 years ago
|
func postFromPostReq(r *http.Request) (post.Post, error) {
|
||
2 years ago
|
|
||
|
p := post.Post{
|
||
|
ID: r.PostFormValue("id"),
|
||
|
Title: r.PostFormValue("title"),
|
||
|
Description: r.PostFormValue("description"),
|
||
|
Tags: strings.Fields(r.PostFormValue("tags")),
|
||
|
Series: r.PostFormValue("series"),
|
||
|
}
|
||
|
|
||
|
// textareas encode newlines as CRLF for historical reasons
|
||
2 years ago
|
p.Body = r.PostFormValue("body")
|
||
2 years ago
|
p.Body = strings.ReplaceAll(p.Body, "\r\n", "\n")
|
||
2 years ago
|
p.Body = strings.TrimSpace(p.Body)
|
||
2 years ago
|
|
||
|
if p.ID == "" ||
|
||
|
p.Title == "" ||
|
||
|
p.Description == "" ||
|
||
|
p.Body == "" ||
|
||
|
len(p.Tags) == 0 {
|
||
|
return post.Post{}, errors.New("ID, Title, Description, Tags, and Body are all required")
|
||
|
}
|
||
2 years ago
|
|
||
2 years ago
|
return p, nil
|
||
2 years ago
|
}
|
||
|
|
||
2 years ago
|
func (a *api) storeAndPublishPost(ctx context.Context, p post.Post) error {
|
||
|
|
||
|
first, err := a.params.PostStore.Set(p, time.Now())
|
||
|
|
||
|
if err != nil {
|
||
|
return fmt.Errorf("storing post with id %q: %w", p.ID, err)
|
||
|
}
|
||
|
|
||
|
if !first {
|
||
|
return nil
|
||
|
}
|
||
|
|
||
|
a.params.Logger.Info(ctx, "publishing blog post to mailing list")
|
||
|
urlStr := a.postURL(p.ID, true)
|
||
|
|
||
|
if err := a.params.MailingList.Publish(p.Title, urlStr); err != nil {
|
||
|
return fmt.Errorf("publishing post to mailing list: %w", err)
|
||
|
}
|
||
|
|
||
|
if err := a.params.PostDraftStore.Delete(p.ID); err != nil {
|
||
|
return fmt.Errorf("deleting draft: %w", err)
|
||
|
}
|
||
|
|
||
|
return nil
|
||
|
}
|
||
|
|
||
|
func (a *api) postPostHandler() http.Handler {
|
||
2 years ago
|
|
||
|
return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
|
||
|
|
||
2 years ago
|
ctx := r.Context()
|
||
|
|
||
2 years ago
|
p, err := postFromPostReq(r)
|
||
|
if err != nil {
|
||
|
apiutil.BadRequest(rw, r, err)
|
||
|
return
|
||
|
}
|
||
2 years ago
|
|
||
2 years ago
|
ctx = mctx.Annotate(ctx, "postID", p.ID)
|
||
2 years ago
|
|
||
2 years ago
|
if err := a.storeAndPublishPost(ctx, p); err != nil {
|
||
2 years ago
|
apiutil.InternalServerError(
|
||
2 years ago
|
rw, r, fmt.Errorf("storing/publishing post with id %q: %w", p.ID, err),
|
||
2 years ago
|
)
|
||
|
return
|
||
|
}
|
||
|
|
||
2 years ago
|
a.executeRedirectTpl(rw, r, a.postURL(p.ID, false))
|
||
2 years ago
|
})
|
||
|
}
|
||
|
|
||
2 years ago
|
func (a *api) deletePostHandler(isDraft bool) http.Handler {
|
||
2 years ago
|
|
||
|
return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
|
||
|
|
||
|
id := filepath.Base(r.URL.Path)
|
||
|
|
||
2 years ago
|
if id == "/" {
|
||
2 years ago
|
apiutil.BadRequest(rw, r, errors.New("id is required"))
|
||
|
return
|
||
|
}
|
||
|
|
||
2 years ago
|
var err error
|
||
|
|
||
|
if isDraft {
|
||
|
err = a.params.PostDraftStore.Delete(id)
|
||
|
} else {
|
||
|
err = a.params.PostStore.Delete(id)
|
||
|
}
|
||
2 years ago
|
|
||
|
if errors.Is(err, post.ErrPostNotFound) {
|
||
|
http.Error(rw, "Post not found", 404)
|
||
|
return
|
||
|
} else if err != nil {
|
||
|
apiutil.InternalServerError(
|
||
|
rw, r, fmt.Errorf("deleting post with id %q: %w", id, err),
|
||
|
)
|
||
|
return
|
||
|
}
|
||
|
|
||
2 years ago
|
if isDraft {
|
||
|
a.executeRedirectTpl(rw, r, a.draftsURL(false))
|
||
|
} else {
|
||
|
a.executeRedirectTpl(rw, r, a.postsURL(false))
|
||
|
}
|
||
2 years ago
|
})
|
||
|
}
|
||
2 years ago
|
|
||
|
func (a *api) previewPostHandler() http.Handler {
|
||
|
|
||
|
tpl := a.mustParseBasedTpl("post.html")
|
||
|
|
||
|
return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
|
||
|
|
||
2 years ago
|
p, err := postFromPostReq(r)
|
||
|
if err != nil {
|
||
|
apiutil.BadRequest(rw, r, err)
|
||
|
return
|
||
|
}
|
||
|
|
||
2 years ago
|
storedPost := post.StoredPost{
|
||
2 years ago
|
Post: p,
|
||
2 years ago
|
PublishedAt: time.Now(),
|
||
|
}
|
||
|
|
||
|
tplPayload, err := a.postToPostTplPayload(storedPost)
|
||
|
|
||
|
if err != nil {
|
||
|
apiutil.InternalServerError(
|
||
|
rw, r, fmt.Errorf("generating template payload: %w", err),
|
||
|
)
|
||
|
return
|
||
|
}
|
||
|
|
||
|
executeTemplate(rw, r, tpl, tplPayload)
|
||
|
})
|
||
|
}
|