Editor: font-size presets + image insert/export support
Two editor features that were in flight alongside the sound work: - FontSize TipTap extension (rides on textStyle) with Small/Normal/Large/ Title presets in the toolbar; StatusBar + CSS support - Image handling: internal/images handler, upload route + config, client API, EditorCore wiring, and md/html/docx export support for images Claude-Session: https://claude.ai/code/session_016Yr6jELuRc7hyzYLccQKZd
This commit is contained in:
@@ -11,6 +11,7 @@ type Config struct {
|
||||
Port string
|
||||
BaseURL string
|
||||
DatabasePath string
|
||||
ImageDir string // on-disk store for editor image uploads
|
||||
|
||||
// LLM
|
||||
LLMBackend string // "vllm" | "ollama"
|
||||
@@ -32,6 +33,7 @@ func Load() *Config {
|
||||
Port: env("PORT", "8080"),
|
||||
BaseURL: env("BASE_URL", "http://localhost:8080"),
|
||||
DatabasePath: env("DATABASE_PATH", "./data/petal.db"),
|
||||
ImageDir: env("IMAGE_DIR", "./data/images"),
|
||||
|
||||
LLMBackend: env("LLM_BACKEND", "vllm"),
|
||||
LLMEndpoint: env("LLM_ENDPOINT", "http://localhost:8000"),
|
||||
|
||||
@@ -92,7 +92,8 @@ type pmNode struct {
|
||||
}
|
||||
|
||||
type pmMark struct {
|
||||
Type string `json:"type"`
|
||||
Type string `json:"type"`
|
||||
Attrs map[string]any `json:"attrs"`
|
||||
}
|
||||
|
||||
// parseDoc decodes Document.Content into a node tree. On empty or malformed JSON
|
||||
@@ -131,6 +132,29 @@ func (n pmNode) hasMark(t string) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
// attrStr returns a string-valued attribute (e.g. an image src), or "".
|
||||
func (n pmNode) attrStr(key string) string {
|
||||
if n.Attrs == nil {
|
||||
return ""
|
||||
}
|
||||
if s, ok := n.Attrs[key].(string); ok {
|
||||
return s
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// markAttr returns a string attribute from the named mark (e.g. a link href).
|
||||
func (n pmNode) markAttr(markType, key string) string {
|
||||
for _, m := range n.Marks {
|
||||
if m.Type == markType && m.Attrs != nil {
|
||||
if s, ok := m.Attrs[key].(string); ok {
|
||||
return s
|
||||
}
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (n pmNode) level() int {
|
||||
if n.Attrs == nil {
|
||||
return 1
|
||||
@@ -173,6 +197,11 @@ func mdBlock(n pmNode, depth int) string {
|
||||
return "```\n" + textContent(n) + "\n```"
|
||||
case "horizontalRule":
|
||||
return "---"
|
||||
case "image":
|
||||
alt := n.attrStr("alt")
|
||||
return fmt.Sprintf("", alt, n.attrStr("src"))
|
||||
case "table":
|
||||
return mdTable(n)
|
||||
case "bulletList", "orderedList":
|
||||
var items []string
|
||||
for i, item := range n.Content {
|
||||
@@ -213,6 +242,55 @@ func mdInline(nodes []pmNode) string {
|
||||
return b.String()
|
||||
}
|
||||
|
||||
// mdTable renders a table node as a GitHub-flavored Markdown table. The first
|
||||
// row is used as the header (Markdown tables require one); a separator row is
|
||||
// inserted after it. Cell text is flattened to inline Markdown.
|
||||
func mdTable(n pmNode) string {
|
||||
var rows [][]string
|
||||
for _, row := range n.Content {
|
||||
if row.Type != "tableRow" {
|
||||
continue
|
||||
}
|
||||
var cells []string
|
||||
for _, cell := range row.Content {
|
||||
// A cell holds block children (usually one paragraph); flatten them.
|
||||
var parts []string
|
||||
for _, c := range cell.Content {
|
||||
parts = append(parts, mdInline(c.Content))
|
||||
}
|
||||
// Escape pipes so cell content doesn't break the column layout.
|
||||
cells = append(cells, strings.ReplaceAll(strings.TrimSpace(strings.Join(parts, " ")), "|", "\\|"))
|
||||
}
|
||||
rows = append(rows, cells)
|
||||
}
|
||||
if len(rows) == 0 {
|
||||
return ""
|
||||
}
|
||||
cols := 0
|
||||
for _, r := range rows {
|
||||
if len(r) > cols {
|
||||
cols = len(r)
|
||||
}
|
||||
}
|
||||
pad := func(r []string) string {
|
||||
for len(r) < cols {
|
||||
r = append(r, "")
|
||||
}
|
||||
return "| " + strings.Join(r, " | ") + " |"
|
||||
}
|
||||
var lines []string
|
||||
lines = append(lines, pad(rows[0]))
|
||||
sep := make([]string, cols)
|
||||
for i := range sep {
|
||||
sep[i] = "---"
|
||||
}
|
||||
lines = append(lines, "| "+strings.Join(sep, " | ")+" |")
|
||||
for _, r := range rows[1:] {
|
||||
lines = append(lines, pad(r))
|
||||
}
|
||||
return strings.Join(lines, "\n")
|
||||
}
|
||||
|
||||
func applyMdMarks(n pmNode) string {
|
||||
t := n.Text
|
||||
if n.hasMark("code") {
|
||||
@@ -230,6 +308,9 @@ func applyMdMarks(n pmNode) string {
|
||||
if n.hasMark("underline") {
|
||||
t = "<u>" + t + "</u>"
|
||||
}
|
||||
if href := n.markAttr("link", "href"); href != "" {
|
||||
t = "[" + t + "](" + href + ")"
|
||||
}
|
||||
return t
|
||||
}
|
||||
|
||||
@@ -347,6 +428,11 @@ func htmlBlock(n pmNode) string {
|
||||
return "<pre><code>" + htmlEscape(textContent(n)) + "</code></pre>\n"
|
||||
case "horizontalRule":
|
||||
return "<hr>\n"
|
||||
case "image":
|
||||
alt := htmlEscape(n.attrStr("alt"))
|
||||
return fmt.Sprintf("<p><img src=\"%s\" alt=\"%s\"></p>\n", htmlEscape(n.attrStr("src")), alt)
|
||||
case "table":
|
||||
return htmlTable(n)
|
||||
case "bulletList", "orderedList":
|
||||
tag := "ul"
|
||||
if n.Type == "orderedList" {
|
||||
@@ -376,6 +462,38 @@ func htmlBlock(n pmNode) string {
|
||||
}
|
||||
}
|
||||
|
||||
// htmlTable renders a table node as an HTML <table>. tableHeader cells become
|
||||
// <th>, tableCell cells become <td>; each cell's block children are flattened
|
||||
// to inline HTML.
|
||||
func htmlTable(n pmNode) string {
|
||||
var b strings.Builder
|
||||
b.WriteString("<table>\n")
|
||||
for _, row := range n.Content {
|
||||
if row.Type != "tableRow" {
|
||||
continue
|
||||
}
|
||||
b.WriteString("<tr>")
|
||||
for _, cell := range row.Content {
|
||||
tag := "td"
|
||||
if cell.Type == "tableHeader" {
|
||||
tag = "th"
|
||||
}
|
||||
var inner strings.Builder
|
||||
for _, c := range cell.Content {
|
||||
if c.Type == "paragraph" {
|
||||
inner.WriteString(htmlInline(c.Content))
|
||||
} else {
|
||||
inner.WriteString(htmlBlock(c))
|
||||
}
|
||||
}
|
||||
b.WriteString("<" + tag + ">" + inner.String() + "</" + tag + ">")
|
||||
}
|
||||
b.WriteString("</tr>\n")
|
||||
}
|
||||
b.WriteString("</table>\n")
|
||||
return b.String()
|
||||
}
|
||||
|
||||
func htmlInline(nodes []pmNode) string {
|
||||
var b strings.Builder
|
||||
for _, n := range nodes {
|
||||
@@ -408,6 +526,12 @@ func applyHTMLMarks(n pmNode) string {
|
||||
if n.hasMark("strike") {
|
||||
t = "<s>" + t + "</s>"
|
||||
}
|
||||
if n.hasMark("highlight") {
|
||||
t = "<mark>" + t + "</mark>"
|
||||
}
|
||||
if href := n.markAttr("link", "href"); href != "" {
|
||||
t = fmt.Sprintf("<a href=\"%s\">%s</a>", htmlEscape(href), t)
|
||||
}
|
||||
return t
|
||||
}
|
||||
|
||||
@@ -500,6 +624,16 @@ func docxBlock(n pmNode) string {
|
||||
return b.String()
|
||||
case "horizontalRule":
|
||||
return `<w:p><w:pPr><w:pBdr><w:bottom w:val="single" w:sz="6" w:space="1" w:color="auto"/></w:pBdr></w:pPr></w:p>`
|
||||
case "image":
|
||||
// Image bytes aren't embedded (that needs media parts); leave a labeled
|
||||
// placeholder so the reader knows an image belonged here.
|
||||
label := n.attrStr("alt")
|
||||
if label == "" {
|
||||
label = "image"
|
||||
}
|
||||
return docxPara(pmNode{Content: []pmNode{{Type: "text", Text: "[" + label + "]", Marks: []pmMark{{Type: "italic"}}}}}, "")
|
||||
case "table":
|
||||
return docxTable(n)
|
||||
case "bulletList", "orderedList":
|
||||
var b strings.Builder
|
||||
for i, item := range n.Content {
|
||||
@@ -520,6 +654,48 @@ func docxBlock(n pmNode) string {
|
||||
}
|
||||
}
|
||||
|
||||
// docxTable renders a table node as a Word table (w:tbl) with single-line
|
||||
// borders. Header cells get a shaded background; every cell's block children are
|
||||
// rendered as paragraphs inside the cell.
|
||||
func docxTable(n pmNode) string {
|
||||
var b strings.Builder
|
||||
b.WriteString(`<w:tbl><w:tblPr><w:tblStyle w:val="TableGrid"/><w:tblW w:w="0" w:type="auto"/>` +
|
||||
`<w:tblBorders>` +
|
||||
`<w:top w:val="single" w:sz="4" w:space="0" w:color="auto"/>` +
|
||||
`<w:left w:val="single" w:sz="4" w:space="0" w:color="auto"/>` +
|
||||
`<w:bottom w:val="single" w:sz="4" w:space="0" w:color="auto"/>` +
|
||||
`<w:right w:val="single" w:sz="4" w:space="0" w:color="auto"/>` +
|
||||
`<w:insideH w:val="single" w:sz="4" w:space="0" w:color="auto"/>` +
|
||||
`<w:insideV w:val="single" w:sz="4" w:space="0" w:color="auto"/>` +
|
||||
`</w:tblBorders></w:tblPr>`)
|
||||
for _, row := range n.Content {
|
||||
if row.Type != "tableRow" {
|
||||
continue
|
||||
}
|
||||
b.WriteString("<w:tr>")
|
||||
for _, cell := range row.Content {
|
||||
b.WriteString("<w:tc><w:tcPr>")
|
||||
if cell.Type == "tableHeader" {
|
||||
b.WriteString(`<w:shd w:val="clear" w:color="auto" w:fill="FFF0F5"/>`)
|
||||
}
|
||||
b.WriteString("</w:tcPr>")
|
||||
// A cell must contain at least one paragraph to be valid.
|
||||
if len(cell.Content) == 0 {
|
||||
b.WriteString("<w:p/>")
|
||||
}
|
||||
for _, c := range cell.Content {
|
||||
b.WriteString(docxBlock(c))
|
||||
}
|
||||
b.WriteString("</w:tc>")
|
||||
}
|
||||
b.WriteString("</w:tr>")
|
||||
}
|
||||
b.WriteString("</w:tbl>")
|
||||
// Word needs a paragraph after a table; otherwise consecutive tables merge.
|
||||
b.WriteString("<w:p/>")
|
||||
return b.String()
|
||||
}
|
||||
|
||||
// docxPara renders a block's inline children as a Word paragraph. An optional
|
||||
// style name (e.g. "Quote") and an optional literal text prefix (for list
|
||||
// markers) may be supplied.
|
||||
@@ -571,6 +747,15 @@ func docxRun(n pmNode) string {
|
||||
if n.hasMark("strike") {
|
||||
props.WriteString("<w:strike/>")
|
||||
}
|
||||
if n.hasMark("highlight") {
|
||||
// Word's text highlight only supports a fixed palette of named colors.
|
||||
props.WriteString(`<w:highlight w:val="yellow"/>`)
|
||||
}
|
||||
if n.markAttr("link", "href") != "" {
|
||||
// Without hyperlink relationships, style links as blue underlined text so
|
||||
// they at least read as links (the URL itself is preserved in md/html).
|
||||
props.WriteString(`<w:color w:val="2563EB"/><w:u w:val="single"/>`)
|
||||
}
|
||||
rpr := ""
|
||||
if props.Len() > 0 {
|
||||
rpr = "<w:rPr>" + props.String() + "</w:rPr>"
|
||||
|
||||
@@ -126,6 +126,77 @@ func TestExportDocx(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// richDocJSON2 exercises the newer node/mark types: links, highlight, an image,
|
||||
// and a table (with a header row). Each export format should carry them through.
|
||||
const richDocJSON2 = `{"type":"doc","content":[` +
|
||||
`{"type":"paragraph","content":[` +
|
||||
`{"type":"text","marks":[{"type":"link","attrs":{"href":"https://petal.test"}}],"text":"site"},` +
|
||||
`{"type":"text","text":" and "},` +
|
||||
`{"type":"text","marks":[{"type":"highlight","attrs":{"color":"#FFF1A8"}}],"text":"lit"}` +
|
||||
`]},` +
|
||||
`{"type":"image","attrs":{"src":"/api/images/abc123.png","alt":"a cat"}},` +
|
||||
`{"type":"table","content":[` +
|
||||
`{"type":"tableRow","content":[` +
|
||||
`{"type":"tableHeader","content":[{"type":"paragraph","content":[{"type":"text","text":"Name"}]}]},` +
|
||||
`{"type":"tableHeader","content":[{"type":"paragraph","content":[{"type":"text","text":"年龄"}]}]}` +
|
||||
`]},` +
|
||||
`{"type":"tableRow","content":[` +
|
||||
`{"type":"tableCell","content":[{"type":"paragraph","content":[{"type":"text","text":"Mei"}]}]},` +
|
||||
`{"type":"tableCell","content":[{"type":"paragraph","content":[{"type":"text","text":"30"}]}]}` +
|
||||
`]}` +
|
||||
`]}` +
|
||||
`]}`
|
||||
|
||||
func seedRichDoc2(t *testing.T, srv http.Handler) string {
|
||||
t.Helper()
|
||||
id := newDoc(t, srv)
|
||||
body := `{"title":"Rich2","content":` + jsonString(richDocJSON2) + `,"content_text":"site and lit\nName 年龄 Mei 30","word_count":6}`
|
||||
if rec := do(t, srv, http.MethodPut, "/"+id, body); rec.Code != http.StatusOK {
|
||||
t.Fatalf("seed rich doc 2: code=%d body=%s", rec.Code, rec.Body)
|
||||
}
|
||||
return id
|
||||
}
|
||||
|
||||
func TestExportLinksImagesTables(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
id := seedRichDoc2(t, srv)
|
||||
|
||||
md := do(t, srv, http.MethodGet, "/"+id+"/export?format=md", "").Body.String()
|
||||
for _, want := range []string{"[site](https://petal.test)", "", "| Name | 年龄 |", "| --- | --- |", "| Mei | 30 |"} {
|
||||
if !strings.Contains(md, want) {
|
||||
t.Fatalf("markdown missing %q in:\n%s", want, md)
|
||||
}
|
||||
}
|
||||
|
||||
html := do(t, srv, http.MethodGet, "/"+id+"/export?format=html", "").Body.String()
|
||||
for _, want := range []string{`<a href="https://petal.test">site</a>`, "<mark>lit</mark>", `<img src="/api/images/abc123.png" alt="a cat">`, "<th>Name</th>", "<td>Mei</td>"} {
|
||||
if !strings.Contains(html, want) {
|
||||
t.Fatalf("html missing %q in:\n%s", want, html)
|
||||
}
|
||||
}
|
||||
|
||||
docx := do(t, srv, http.MethodGet, "/"+id+"/export?format=docx", "")
|
||||
raw := docx.Body.Bytes()
|
||||
zr, err := zip.NewReader(bytes.NewReader(raw), int64(len(raw)))
|
||||
if err != nil {
|
||||
t.Fatalf("docx not a zip: %v", err)
|
||||
}
|
||||
var docXML string
|
||||
for _, f := range zr.File {
|
||||
if f.Name == "word/document.xml" {
|
||||
rc, _ := f.Open()
|
||||
b, _ := io.ReadAll(rc)
|
||||
rc.Close()
|
||||
docXML = string(b)
|
||||
}
|
||||
}
|
||||
for _, want := range []string{"<w:tbl>", "Name", "年龄", "[a cat]", "<w:highlight"} {
|
||||
if !strings.Contains(docXML, want) {
|
||||
t.Fatalf("docx document.xml missing %q", want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestExportUnsupportedFormat(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
id := newDoc(t, srv)
|
||||
|
||||
132
internal/images/handler.go
Normal file
132
internal/images/handler.go
Normal file
@@ -0,0 +1,132 @@
|
||||
// Package images implements a tiny content-addressed image store: writers upload
|
||||
// images from the editor, they're saved to disk under the configured directory,
|
||||
// and served back by hashed filename. Content addressing means the same image
|
||||
// pasted twice is stored once, and URLs are stable and cacheable forever.
|
||||
package images
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
)
|
||||
|
||||
// maxUploadBytes caps a single image at 10 MiB — generous for a writing tool,
|
||||
// small enough to keep a careless paste from filling the disk.
|
||||
const maxUploadBytes = 10 << 20
|
||||
|
||||
// extByContentType maps the image types we accept to a canonical extension. The
|
||||
// allowlist doubles as validation: anything not here is rejected.
|
||||
var extByContentType = map[string]string{
|
||||
"image/png": ".png",
|
||||
"image/jpeg": ".jpg",
|
||||
"image/gif": ".gif",
|
||||
"image/webp": ".webp",
|
||||
"image/svg+xml": ".svg",
|
||||
}
|
||||
|
||||
// Handler serves the upload + fetch endpoints, backed by a directory on disk.
|
||||
type Handler struct {
|
||||
dir string
|
||||
}
|
||||
|
||||
// New constructs a Handler, ensuring the storage directory exists.
|
||||
func New(dir string) (*Handler, error) {
|
||||
if err := os.MkdirAll(dir, 0o755); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &Handler{dir: dir}, nil
|
||||
}
|
||||
|
||||
// Routes mounts the image endpoints. Mount under "/images" so the full paths are
|
||||
// POST /api/images (upload) and GET /api/images/{name} (fetch).
|
||||
func (h *Handler) Routes() chi.Router {
|
||||
r := chi.NewRouter()
|
||||
r.Post("/", h.upload)
|
||||
r.Get("/{name}", h.serve)
|
||||
return r
|
||||
}
|
||||
|
||||
// upload accepts a single multipart "image" field, sniffs and validates its
|
||||
// type, and writes it under a content hash so identical images dedupe. Responds
|
||||
// with the served URL the editor inserts.
|
||||
func (h *Handler) upload(w http.ResponseWriter, r *http.Request) {
|
||||
r.Body = http.MaxBytesReader(w, r.Body, maxUploadBytes)
|
||||
file, _, err := r.FormFile("image")
|
||||
if err != nil {
|
||||
http.Error(w, "expected an 'image' file field", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
data, err := io.ReadAll(file)
|
||||
if err != nil {
|
||||
http.Error(w, "could not read upload", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
// Trust a sniff over the client-declared type. SVG isn't reliably sniffable
|
||||
// (DetectContentType returns text/plain or text/xml), so fall back to a
|
||||
// lightweight tag check for it.
|
||||
ct := http.DetectContentType(data)
|
||||
ext, ok := extByContentType[ct]
|
||||
if !ok {
|
||||
if looksLikeSVG(data) {
|
||||
ext, ok = ".svg", true
|
||||
}
|
||||
}
|
||||
if !ok {
|
||||
http.Error(w, "unsupported image type", http.StatusUnsupportedMediaType)
|
||||
return
|
||||
}
|
||||
|
||||
sum := sha256.Sum256(data)
|
||||
name := hex.EncodeToString(sum[:])[:32] + ext
|
||||
path := filepath.Join(h.dir, name)
|
||||
|
||||
// Skip the write if this exact content is already stored.
|
||||
if _, statErr := os.Stat(path); errors.Is(statErr, os.ErrNotExist) {
|
||||
if err := os.WriteFile(path, data, 0o644); err != nil {
|
||||
http.Error(w, "could not store image", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_ = json.NewEncoder(w).Encode(map[string]string{"url": "/api/images/" + name})
|
||||
}
|
||||
|
||||
// serve returns a stored image by its hashed filename. The filename is validated
|
||||
// to be a bare name (no path separators) so it can't escape the storage dir, and
|
||||
// served with a long-lived cache header since content-addressed URLs never change.
|
||||
func (h *Handler) serve(w http.ResponseWriter, r *http.Request) {
|
||||
name := chi.URLParam(r, "name")
|
||||
if name == "" || name != filepath.Base(name) || strings.ContainsAny(name, `/\`) {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
path := filepath.Join(h.dir, filepath.Base(name))
|
||||
if _, err := os.Stat(path); err != nil {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Cache-Control", "public, max-age=31536000, immutable")
|
||||
http.ServeFile(w, r, path)
|
||||
}
|
||||
|
||||
// looksLikeSVG does a cheap check for an <svg root tag near the start of the
|
||||
// file, since DetectContentType doesn't recognize SVG.
|
||||
func looksLikeSVG(data []byte) bool {
|
||||
head := data
|
||||
if len(head) > 512 {
|
||||
head = head[:512]
|
||||
}
|
||||
return strings.Contains(strings.ToLower(string(head)), "<svg")
|
||||
}
|
||||
97
internal/images/handler_test.go
Normal file
97
internal/images/handler_test.go
Normal file
@@ -0,0 +1,97 @@
|
||||
package images
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"mime/multipart"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// a 1x1 transparent PNG.
|
||||
var pngBytes = []byte{
|
||||
0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52,
|
||||
0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x08, 0x06, 0x00, 0x00, 0x00, 0x1f, 0x15, 0xc4,
|
||||
0x89, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x44, 0x41, 0x54, 0x78, 0x9c, 0x62, 0x00, 0x01, 0x00, 0x00,
|
||||
0x05, 0x00, 0x01, 0x0d, 0x0a, 0x2d, 0xb4, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44, 0xae,
|
||||
0x42, 0x60, 0x82,
|
||||
}
|
||||
|
||||
func uploadReq(t *testing.T, field string, data []byte) *http.Request {
|
||||
t.Helper()
|
||||
var buf bytes.Buffer
|
||||
mw := multipart.NewWriter(&buf)
|
||||
fw, err := mw.CreateFormFile(field, "x.png")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
fw.Write(data)
|
||||
mw.Close()
|
||||
req := httptest.NewRequest(http.MethodPost, "/", &buf)
|
||||
req.Header.Set("Content-Type", mw.FormDataContentType())
|
||||
return req
|
||||
}
|
||||
|
||||
func TestUploadAndServe(t *testing.T) {
|
||||
h, err := New(t.TempDir())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r := h.Routes()
|
||||
|
||||
// Upload a PNG → expect a JSON url under /api/images/.
|
||||
rec := httptest.NewRecorder()
|
||||
r.ServeHTTP(rec, uploadReq(t, "image", pngBytes))
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("upload code=%d body=%s", rec.Code, rec.Body)
|
||||
}
|
||||
var resp struct{ URL string }
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !strings.HasPrefix(resp.URL, "/api/images/") || !strings.HasSuffix(resp.URL, ".png") {
|
||||
t.Fatalf("unexpected url %q", resp.URL)
|
||||
}
|
||||
|
||||
// The same content uploaded again dedupes to the same URL.
|
||||
rec2 := httptest.NewRecorder()
|
||||
r.ServeHTTP(rec2, uploadReq(t, "image", pngBytes))
|
||||
var resp2 struct{ URL string }
|
||||
json.Unmarshal(rec2.Body.Bytes(), &resp2)
|
||||
if resp2.URL != resp.URL {
|
||||
t.Fatalf("expected dedup to same url, got %q vs %q", resp2.URL, resp.URL)
|
||||
}
|
||||
|
||||
// Fetch it back.
|
||||
name := strings.TrimPrefix(resp.URL, "/api/images/")
|
||||
rec3 := httptest.NewRecorder()
|
||||
r.ServeHTTP(rec3, httptest.NewRequest(http.MethodGet, "/"+name, nil))
|
||||
if rec3.Code != http.StatusOK {
|
||||
t.Fatalf("serve code=%d", rec3.Code)
|
||||
}
|
||||
if !bytes.Equal(rec3.Body.Bytes(), pngBytes) {
|
||||
t.Fatal("served bytes differ from uploaded")
|
||||
}
|
||||
}
|
||||
|
||||
func TestUploadRejectsNonImage(t *testing.T) {
|
||||
h, _ := New(t.TempDir())
|
||||
r := h.Routes()
|
||||
rec := httptest.NewRecorder()
|
||||
r.ServeHTTP(rec, uploadReq(t, "image", []byte("this is plainly not an image at all")))
|
||||
if rec.Code != http.StatusUnsupportedMediaType {
|
||||
t.Fatalf("expected 415, got %d", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestServeMissing(t *testing.T) {
|
||||
h, _ := New(t.TempDir())
|
||||
r := h.Routes()
|
||||
rec := httptest.NewRecorder()
|
||||
r.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/deadbeef.png", nil))
|
||||
if rec.Code != http.StatusNotFound {
|
||||
t.Fatalf("expected 404, got %d", rec.Code)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user