package http import ( "bytes" "context" "errors" "fmt" "html/template" "net/http" "path/filepath" "strings" "time" "dev.mediocregopher.com/mediocre-blog.git/src/http/apiutil" "dev.mediocregopher.com/mediocre-blog.git/src/post" "dev.mediocregopher.com/mediocre-blog.git/src/post/asset" "dev.mediocregopher.com/mediocre-blog.git/src/render" "dev.mediocregopher.com/mediocre-go-lib.git/mctx" ) type postPreprocessFuncs struct { urlBuilder render.URLBuilder imageTpl *template.Template } func newPostPreprocessFuncs(urlBuilder render.URLBuilder) postPreprocessFuncs { imageTpl := template.New("image.html") imageTpl = template.Must(imageTpl.Parse(mustReadTplFile("image.html"))) return postPreprocessFuncs{urlBuilder, imageTpl} } func (f postPreprocessFuncs) Image(args ...string) (string, error) { var ( id = args[0] descr = "TODO" ) if len(args) > 1 { descr = args[1] } var ( tplPayload = struct { RootURL render.URLBuilder ID string Descr string Resizable bool }{ RootURL: f.urlBuilder, ID: id, Descr: descr, Resizable: asset.IsImageResizable(id), } buf = new(bytes.Buffer) ) err := f.imageTpl.ExecuteTemplate(buf, "image.html", tplPayload) if err != nil { return "", err } return buf.String(), nil } func (a *api) getPostsHandler() http.Handler { var ( tpl = a.mustParseBasedTpl("posts.html") getPostHandler = a.getPostHandler() ) return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { if id := filepath.Base(r.URL.Path); id != "/" { getPostHandler.ServeHTTP(rw, r) return } a.executeTemplate(rw, r, tpl, nil) }) } func (a *api) getPostHandler() http.Handler { tpl := a.mustParseBasedTpl("post.html") return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { a.executeTemplate(rw, r, tpl, nil) }) } func (a *api) managePostsHandler() http.Handler { tpl := a.mustParseBasedTpl("posts-manage.html") return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { a.executeTemplate(rw, r, tpl, nil) }) } func (a *api) editPostHandler(isDraft bool) http.Handler { tpl := a.mustParseBasedTpl("post-edit.html") return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { a.executeTemplate(rw, r, tpl, struct { IsDraft bool Formats []post.Format }{ IsDraft: isDraft, Formats: post.Formats, }) }) } func postFromPostReq(r *http.Request) (post.Post, error) { formatStr := r.PostFormValue("format") if formatStr == "" { return post.Post{}, errors.New("format is required") } format, err := post.FormatFromString(formatStr) if err != nil { return post.Post{}, fmt.Errorf("parsing format: %w", err) } 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"), Format: format, } // textareas encode newlines as CRLF for historical reasons p.Body = r.PostFormValue("body") p.Body = strings.ReplaceAll(p.Body, "\r\n", "\n") p.Body = strings.TrimSpace(p.Body) if p.ID == "" || p.Title == "" || p.Body == "" || len(p.Tags) == 0 { return post.Post{}, errors.New("id, ritle, tags, and body are all required") } return p, nil } func (a *api) publishPost(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 } 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 { return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { var ( ctx = r.Context() logger = a.params.Logger ) p, err := postFromPostReq(r) if err != nil { apiutil.BadRequest(ctx, logger, rw, "%w", err) return } ctx = mctx.Annotate(ctx, "postID", p.ID) if err := a.publishPost(ctx, p); err != nil { apiutil.InternalServerError( ctx, logger, rw, "publishing post with id %q: %w", p.ID, err, ) return } a.executeRedirectTpl( rw, r, a.urlBuilder.Post(p.ID).MethodEdit().String(), ) }) } func (a *api) deletePostHandler(isDraft bool) http.Handler { return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { var ( ctx = r.Context() logger = a.params.Logger id = filepath.Base(r.URL.Path) ) if id == "/" { apiutil.BadRequest(ctx, logger, rw, "id is required") return } var err error if isDraft { err = a.params.PostDraftStore.Delete(id) } else { err = a.params.PostStore.Delete(id) } if errors.Is(err, post.ErrPostNotFound) { http.Error(rw, "Post not found", 404) return } else if err != nil { apiutil.InternalServerError( ctx, logger, rw, "deleting post with id %q: %w", id, err, ) return } if isDraft { a.executeRedirectTpl( rw, r, a.urlBuilder.Drafts().MethodManage().String(), ) } else { a.executeRedirectTpl( rw, r, a.urlBuilder.Posts().MethodManage().String(), ) } }) } func (a *api) previewPostHandler() http.Handler { tpl := a.mustParseBasedTpl("post.html") return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { var ( ctx = r.Context() logger = a.params.Logger ) p, err := postFromPostReq(r) if err != nil { apiutil.BadRequest(ctx, logger, rw, "%w", err) return } storedPost := post.StoredPost{ Post: p, PublishedAt: time.Now(), } r = r.WithContext(render.WithPost(ctx, storedPost)) a.executeTemplate(rw, r, tpl, nil) }) }