feat: add /api/files to apps/posts
01f3fefe
5 file(s) · +147 −2
| 45 | 45 | optional `title`, `slug`, `status` (`draft`|`published`, default `draft`), |
|
| 46 | 46 | `alias`, `canonical_url`, `published_date`, `meta_description`, |
|
| 47 | 47 | `meta_image`, `lang`, `tags`, `weather`. |
|
| 48 | + | - `POST /api/files` uploads a file (same `X-API-Key` auth). Multipart form: |
|
| 49 | + | `file` (required, 10 MB max) and optional `name`, which becomes the stored |
|
| 50 | + | filename (slugified, extension kept or taken from the upload; 409 if taken). |
|
| 51 | + | Without `name` a random ID is used. Returns 201 with JSON `url`, |
|
| 52 | + | `filename`, `original_name`, `content_type`, `size`. |
|
| 48 | 53 | ||
| 49 | 54 | See `.env.example`. |
| 1 | 1 | package main |
|
| 2 | 2 | ||
| 3 | 3 | import ( |
|
| 4 | + | "io" |
|
| 4 | 5 | "net/http" |
|
| 5 | 6 | "strconv" |
|
| 6 | 7 | "strings" |
|
| 7 | 8 | ||
| 9 | + | "github.com/stevedylandev/andromeda/pkg/auth" |
|
| 8 | 10 | "github.com/stevedylandev/andromeda/pkg/web" |
|
| 9 | 11 | ) |
|
| 10 | 12 | ||
| 172 | 174 | } |
|
| 173 | 175 | web.WriteJSON(w, http.StatusCreated, toDetail(*post)) |
|
| 174 | 176 | } |
|
| 177 | + | ||
| 178 | + | type apiFile struct { |
|
| 179 | + | URL string `json:"url"` |
|
| 180 | + | Filename string `json:"filename"` |
|
| 181 | + | OriginalName string `json:"original_name"` |
|
| 182 | + | ContentType string `json:"content_type"` |
|
| 183 | + | Size int64 `json:"size"` |
|
| 184 | + | } |
|
| 185 | + | ||
| 186 | + | func (a *App) apiUploadFile(w http.ResponseWriter, r *http.Request) { |
|
| 187 | + | r.Body = http.MaxBytesReader(w, r.Body, bodyLimit) |
|
| 188 | + | if err := r.ParseMultipartForm(uploadMaxBytes); err != nil { |
|
| 189 | + | web.WriteError(w, http.StatusBadRequest, "failed to read multipart form") |
|
| 190 | + | return |
|
| 191 | + | } |
|
| 192 | + | file, header, err := r.FormFile("file") |
|
| 193 | + | if err != nil { |
|
| 194 | + | web.WriteError(w, http.StatusBadRequest, "file is required") |
|
| 195 | + | return |
|
| 196 | + | } |
|
| 197 | + | defer file.Close() |
|
| 198 | + | data, err := io.ReadAll(file) |
|
| 199 | + | if err != nil { |
|
| 200 | + | web.WriteError(w, http.StatusBadRequest, "failed to read upload") |
|
| 201 | + | return |
|
| 202 | + | } |
|
| 203 | + | if int64(len(data)) > uploadMaxBytes { |
|
| 204 | + | web.WriteError(w, http.StatusRequestEntityTooLarge, "file exceeds 10MB limit") |
|
| 205 | + | return |
|
| 206 | + | } |
|
| 207 | + | originalName := "upload" |
|
| 208 | + | contentType := "application/octet-stream" |
|
| 209 | + | if header != nil { |
|
| 210 | + | originalName = header.Filename |
|
| 211 | + | if ct := header.Header.Get("Content-Type"); ct != "" { |
|
| 212 | + | contentType = ct |
|
| 213 | + | } |
|
| 214 | + | } |
|
| 215 | + | ext := "" |
|
| 216 | + | if i := strings.LastIndex(originalName, "."); i > 0 && i < len(originalName)-1 { |
|
| 217 | + | ext = originalName[i+1:] |
|
| 218 | + | } |
|
| 219 | + | ||
| 220 | + | var stored string |
|
| 221 | + | if name := strings.TrimSpace(r.FormValue("name")); name != "" { |
|
| 222 | + | stored = sanitizeFilename(name, ext) |
|
| 223 | + | if stored == "" { |
|
| 224 | + | web.WriteError(w, http.StatusBadRequest, "name must contain letters or numbers") |
|
| 225 | + | return |
|
| 226 | + | } |
|
| 227 | + | originalName = name |
|
| 228 | + | } else { |
|
| 229 | + | id, err := auth.GenerateShortID(10) |
|
| 230 | + | if err != nil { |
|
| 231 | + | web.WriteError(w, http.StatusInternalServerError, "internal server error") |
|
| 232 | + | return |
|
| 233 | + | } |
|
| 234 | + | stored = id |
|
| 235 | + | if ext != "" { |
|
| 236 | + | stored = id + "." + ext |
|
| 237 | + | } |
|
| 238 | + | } |
|
| 239 | + | ||
| 240 | + | backend := a.Storage |
|
| 241 | + | if backend == nil { |
|
| 242 | + | web.WriteError(w, http.StatusInternalServerError, "storage not configured") |
|
| 243 | + | return |
|
| 244 | + | } |
|
| 245 | + | existing, err := getFileByFilename(a.DB, stored) |
|
| 246 | + | if err != nil { |
|
| 247 | + | web.WriteError(w, http.StatusInternalServerError, "internal server error") |
|
| 248 | + | return |
|
| 249 | + | } |
|
| 250 | + | if existing != nil { |
|
| 251 | + | web.WriteError(w, http.StatusConflict, "file with that name already exists") |
|
| 252 | + | return |
|
| 253 | + | } |
|
| 254 | + | // Record before writing to storage so the UNIQUE filename constraint keeps |
|
| 255 | + | // two concurrent uploads with the same name from overwriting each other. |
|
| 256 | + | rec, err := createFile(a.DB, stored, originalName, contentType, int64(len(data)), backend.Name()) |
|
| 257 | + | if err != nil { |
|
| 258 | + | if strings.Contains(err.Error(), "UNIQUE") { |
|
| 259 | + | web.WriteError(w, http.StatusConflict, "file with that name already exists") |
|
| 260 | + | return |
|
| 261 | + | } |
|
| 262 | + | a.Log.Error("api record file", "err", err) |
|
| 263 | + | web.WriteError(w, http.StatusInternalServerError, "failed to record file") |
|
| 264 | + | return |
|
| 265 | + | } |
|
| 266 | + | if err := backend.Put(r.Context(), stored, contentType, data); err != nil { |
|
| 267 | + | a.Log.Error("api save file", "backend", backend.Name(), "err", err) |
|
| 268 | + | _, _ = deleteFile(a.DB, rec.ShortID) |
|
| 269 | + | web.WriteError(w, http.StatusInternalServerError, "failed to save file") |
|
| 270 | + | return |
|
| 271 | + | } |
|
| 272 | + | web.WriteJSON(w, http.StatusCreated, apiFile{ |
|
| 273 | + | URL: a.SiteURL + "/files/" + rec.Filename, |
|
| 274 | + | Filename: rec.Filename, |
|
| 275 | + | OriginalName: rec.OriginalName, |
|
| 276 | + | ContentType: rec.ContentType, |
|
| 277 | + | Size: rec.Size, |
|
| 278 | + | }) |
|
| 279 | + | } |
|
| 41 | 41 | mux.HandleFunc("GET /api/posts", cors(a.apiListPosts)) |
|
| 42 | 42 | mux.HandleFunc("GET /api/posts/{slug}", cors(a.apiGetPost)) |
|
| 43 | 43 | mux.HandleFunc("POST /api/posts", requireAPIKey(a.apiCreatePost)) |
|
| 44 | + | mux.HandleFunc("POST /api/files", requireAPIKey(a.apiUploadFile)) |
|
| 44 | 45 | ||
| 45 | 46 | // Admin auth |
|
| 46 | 47 | mux.HandleFunc("GET /admin/login", a.loginGet) |
| 475 | 475 | CatSleet: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256"><!-- Icon from Phosphor by Phosphor Icons - https://github.com/phosphor-icons/core/blob/main/LICENSE --><path fill="currentColor" d="M84 196a8 8 0 1 1-8-8a8 8 0 0 1 8 8m32 8a8 8 0 1 0 8 8a8 8 0 0 0-8-8m48-16a8 8 0 1 0 8 8a8 8 0 0 0-8-8m-96 40a8 8 0 1 0 8 8a8 8 0 0 0-8-8m88 0a8 8 0 1 0 8 8a8 8 0 0 0-8-8m72-136a72.08 72.08 0 0 1-72 72H76a48 48 0 1 1 11.51-94.61A72.08 72.08 0 0 1 228 92m-8 0a64.06 64.06 0 0 0-128-3.77a4 4 0 0 1-8-.46a71.6 71.6 0 0 1 1.42-10.65A40 40 0 1 0 76 156h80a64.07 64.07 0 0 0 64-64"/></svg>`, |
|
| 476 | 476 | CatFog: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256"><!-- Icon from Phosphor by Phosphor Icons - https://github.com/phosphor-icons/core/blob/main/LICENSE --><path fill="currentColor" d="M120 204H72a4 4 0 0 1 0-8h48a4 4 0 0 1 0 8m64-8h-24a4 4 0 0 0 0 8h24a4 4 0 0 0 0-8m-24 32h-56a4 4 0 0 0 0 8h56a4 4 0 0 0 0-8m68-128a72.08 72.08 0 0 1-72 72H76a48 48 0 1 1 11.51-94.61A72.08 72.08 0 0 1 228 100m-8 0a64.06 64.06 0 0 0-128-3.77a4 4 0 0 1-8-.46a71.6 71.6 0 0 1 1.42-10.65A40 40 0 1 0 76 164h80a64.07 64.07 0 0 0 64-64"/></svg>`, |
|
| 477 | 477 | } |
|
| 478 | + | ||
| 479 | + | // sanitizeFilename turns a user-supplied name into a safe stored filename. |
|
| 480 | + | // The base is slugified and the extension is kept (alphanumerics only). If |
|
| 481 | + | // name has no extension, fallbackExt is used. Returns "" if nothing usable |
|
| 482 | + | // remains. |
|
| 483 | + | func sanitizeFilename(name, fallbackExt string) string { |
|
| 484 | + | name = strings.TrimSpace(name) |
|
| 485 | + | base, ext := name, "" |
|
| 486 | + | if i := strings.LastIndex(name, "."); i > 0 && i < len(name)-1 { |
|
| 487 | + | base, ext = name[:i], name[i+1:] |
|
| 488 | + | } |
|
| 489 | + | base = slugify(base) |
|
| 490 | + | if base == "" { |
|
| 491 | + | return "" |
|
| 492 | + | } |
|
| 493 | + | if ext == "" { |
|
| 494 | + | ext = fallbackExt |
|
| 495 | + | } |
|
| 496 | + | ext = strings.ReplaceAll(slugify(ext), "-", "") |
|
| 497 | + | if ext == "" { |
|
| 498 | + | return base |
|
| 499 | + | } |
|
| 500 | + | return base + "." + ext |
|
| 501 | + | } |
| 22 | 22 | | Variable | Description | Default | |
|
| 23 | 23 | |---|---|---| |
|
| 24 | 24 | | `POSTS_PASSWORD` | Password for admin login | `changeme` | |
|
| 25 | - | | `POSTS_API_KEY` | API key for creating posts via `POST /api/posts` | _(unset)_ | |
|
| 25 | + | | `POSTS_API_KEY` | API key for `POST /api/posts` and `POST /api/files` | _(unset)_ | |
|
| 26 | 26 | | `POSTS_DB_PATH` | SQLite database file path | `posts.sqlite` | |
|
| 27 | 27 | | `UPLOADS_DIR` | Directory for uploaded files (used when R2 unset) | `uploads` | |
|
| 28 | 28 | | `SITE_URL` | Public URL for RSS feed and links | `http://localhost:3000` | |
|
| 37 | 37 | ||
| 38 | 38 | Upload storage falls back to local filesystem (`UPLOADS_DIR`) when `R2_BUCKET` is empty. Set all five `R2_*` variables to switch uploads to Cloudflare R2. |
|
| 39 | 39 | ||
| 40 | - | If `POSTS_API_KEY` is not set, `POST /api/posts` returns `403`. The read-only `GET` endpoints are always public. |
|
| 40 | + | If `POSTS_API_KEY` is not set, `POST /api/posts` and `POST /api/files` return `403`. The read-only `GET` endpoints are always public. |
|
| 41 | 41 | ||
| 42 | 42 | ## Deploy |
|
| 43 | 43 | ||
| 87 | 87 | | `GET` | `/api/posts?limit=30` | List published posts | |
|
| 88 | 88 | | `GET` | `/api/posts/{slug}` | Get a published post by slug | |
|
| 89 | 89 | | `POST` | `/api/posts` | Create a post | |
|
| 90 | + | | `POST` | `/api/files` | Upload a file | |
|
| 90 | 91 | ||
| 91 | 92 | `POST /api/posts` requires an `x-api-key` header matching `POSTS_API_KEY`. The JSON body accepts: |
|
| 92 | 93 | ||
| 112 | 113 | -H "x-api-key: $POSTS_API_KEY" \ |
|
| 113 | 114 | -H "Content-Type: application/json" \ |
|
| 114 | 115 | -d '{"title": "Hello World", "content": "My first post via the API", "status": "published"}' |
|
| 116 | + | ``` |
|
| 117 | + | ||
| 118 | + | `POST /api/files` uses the same `x-api-key` header and takes `multipart/form-data` with a `file` field (max 10 MB) and an optional `name` field to set the filename. Returns `201` with the file's `url`, `filename`, `original_name`, `content_type`, and `size`, or `409` if the name is taken. |
|
| 119 | + | ||
| 120 | + | ```bash |
|
| 121 | + | curl -X POST https://your-posts-instance.com/api/files \ |
|
| 122 | + | -H "x-api-key: $POSTS_API_KEY" \ |
|
| 123 | + | -F file=@photo.png \ |
|
| 124 | + | -F name=my-photo |
|
| 115 | 125 | ``` |
|
| 116 | 126 | ||
| 117 | 127 | ## Acknowledgements |
|