photo-object-storage: MinIO on .13 (9010/9011), Go upload+serve /photos, admin S3 disk + Filament upload, migrated, deployed

This commit is contained in:
2026-08-08 10:01:02 +10:00
parent 61f16742ca
commit d5919315fa
9 changed files with 246 additions and 32 deletions

View File

@@ -10,6 +10,7 @@ import (
"wherewoof/frontend/internal/auth"
"wherewoof/frontend/internal/db"
"wherewoof/frontend/internal/sms"
"wherewoof/frontend/internal/storage"
)
// Templates maps a page key to its parsed template set (base + page + partials).
@@ -22,11 +23,12 @@ type App struct {
Queries *db.Queries
Tpl Templates
Sender sms.Sender
Storage *storage.Client
}
// New returns an App with the given query layer, template sets, and SMS sender.
func New(queries *db.Queries, tpl Templates, sender sms.Sender) *App {
return &App{Queries: queries, Tpl: tpl, Sender: sender}
// New returns an App with the given query layer, template sets, SMS sender, and object storage.
func New(queries *db.Queries, tpl Templates, sender sms.Sender, store *storage.Client) *App {
return &App{Queries: queries, Tpl: tpl, Sender: sender, Storage: store}
}
// PageData is the root data passed to the base layout.

View File

@@ -0,0 +1,39 @@
package handlers
import (
"errors"
"io"
"net/http"
"strings"
"github.com/minio/minio-go/v7"
)
// ServePhoto streams a photo object from object storage.
// Used by tags.photo_url values of the form "/photos/tags/{id}.{ext}".
func (a *App) ServePhoto(w http.ResponseWriter, r *http.Request) {
key := strings.TrimPrefix(r.PathValue("key"), "/")
if key == "" || a.Storage == nil {
http.NotFound(w, r)
return
}
obj, ct, err := a.Storage.Get(r.Context(), key)
if err != nil {
var me minio.ErrorResponse
if errors.As(err, &me) && me.Code == "NoSuchKey" {
http.NotFound(w, r)
return
}
http.Error(w, "photo unavailable", http.StatusInternalServerError)
return
}
defer obj.Close()
if ct == "" {
ct = "application/octet-stream"
}
w.Header().Set("Content-Type", ct)
w.Header().Set("Cache-Control", "public, max-age=86400")
_, _ = io.Copy(w, obj)
}

View File

@@ -3,9 +3,7 @@ package handlers
import (
"errors"
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"strconv"
"strings"
@@ -173,13 +171,18 @@ func (a *App) loadOwnedTag(w http.ResponseWriter, r *http.Request, uid int64) (d
return tag, true
}
// UploadPhoto saves an uploaded image for a tag and sets its photo_url (HTMX).
// UploadPhoto saves an uploaded image for a tag to object storage (MinIO) and
// sets its photo_url to the app's serve path (HTMX).
func (a *App) UploadPhoto(w http.ResponseWriter, r *http.Request) {
uid, _ := auth.GetUserID(r)
tag, ok := a.loadOwnedTag(w, r, uid)
if !ok {
return
}
if a.Storage == nil {
writeUploadMsg(w, "Photo storage is not configured.")
return
}
if err := r.ParseMultipartForm(5 << 20); err != nil { // 5 MB
writeUploadMsg(w, "Upload too large (max 5 MB).")
@@ -196,34 +199,27 @@ func (a *App) UploadPhoto(w http.ResponseWriter, r *http.Request) {
writeUploadMsg(w, "Upload too large (max 5 MB).")
return
}
if !strings.HasPrefix(header.Header.Get("Content-Type"), "image/") {
ct := header.Header.Get("Content-Type")
if !strings.HasPrefix(ct, "image/") {
writeUploadMsg(w, "Only image files are allowed.")
return
}
// Sanitise the filename and store under uploads/.
ext := strings.ToLower(filepath.Ext(header.Filename))
if ext == "" {
ext = ".jpg"
}
dst := filepath.Join("static", "uploads", fmt.Sprintf("tag%d%s", tag.ID, ext))
out, err := os.Create(dst)
if err != nil {
writeUploadMsg(w, "Could not save the photo.")
return
}
defer out.Close()
if _, err := io.Copy(out, file); err != nil {
key := fmt.Sprintf("tags/%d%s", tag.ID, ext)
if err := a.Storage.Put(r.Context(), key, file, header.Size, ct); err != nil {
fmt.Println("upload to storage failed:", err)
writeUploadMsg(w, "Could not save the photo.")
return
}
photoURL := "/static/uploads/" + filepath.Base(dst)
photoURL := "/photos/" + key
if _, err := a.Queries.UpdateTagDetails(r.Context(), db.UpdateTagDetailsParams{
ID: tag.ID,
PhotoUrl: pgtype.Text{String: photoURL, Valid: true},
// Preserve existing values: re-send them via the form is not possible here,
// so use the stored tag fields for everything else.
ItemType: tag.ItemType, Description: tag.Description, Phone: tag.Phone,
Address: tag.Address, Notes: tag.Notes, SmsEnabled: tag.SmsEnabled,
}); err != nil {
@@ -232,7 +228,7 @@ func (a *App) UploadPhoto(w http.ResponseWriter, r *http.Request) {
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
fmt.Fprintf(w, `<p class="mt-2 text-xs text-green-700">Photo uploaded ✓ <a href="%s" class="underline">view</a> — refresh to see it on the tag page.</p>`, photoURL)
fmt.Fprintf(w, `<p class="mt-2 text-xs text-green-700">Photo uploaded ✓ — refresh to see it on the tag page.</p>`)
}
func writeUploadMsg(w http.ResponseWriter, msg string) {

View File

@@ -0,0 +1,99 @@
// Package storage provides object storage for Where Woof photos (MinIO, S3-compatible).
package storage
import (
"context"
"fmt"
"io"
"os"
"time"
"github.com/minio/minio-go/v7"
"github.com/minio/minio-go/v7/pkg/credentials"
)
// Client wraps a MinIO client and bucket for photo objects.
type Client struct {
mc *minio.Client
bucket string
}
// NewClient builds a storage client from MINIO_* env vars.
// Returns (nil, nil) when storage is not configured (MINIO_ENDPOINT unset) —
// callers should treat that as "storage unavailable".
func NewClient() (*Client, error) {
endpoint := os.Getenv("MINIO_ENDPOINT")
if endpoint == "" {
return nil, nil
}
access := os.Getenv("MINIO_ACCESS_KEY")
secret := os.Getenv("MINIO_SECRET_KEY")
bucket := os.Getenv("MINIO_BUCKET")
if bucket == "" {
bucket = "wherewoof"
}
mc, err := minio.New(endpoint, &minio.Options{
Creds: credentials.NewStaticV4(access, secret, ""),
Secure: false, // internal LAN
})
if err != nil {
return nil, fmt.Errorf("minio client: %w", err)
}
return &Client{mc: mc, bucket: bucket}, nil
}
// Put stores an object under key and returns the size.
func (c *Client) Put(ctx context.Context, key string, r io.Reader, size int64, contentType string) error {
if c == nil {
return fmt.Errorf("storage not configured")
}
_, err := c.mc.PutObject(ctx, c.bucket, key, r, size, minio.PutObjectOptions{
ContentType: contentType,
})
return err
}
// Get returns the object reader + content type for a key.
func (c *Client) Get(ctx context.Context, key string) (io.ReadCloser, string, error) {
if c == nil {
return nil, "", fmt.Errorf("storage not configured")
}
obj, err := c.mc.GetObject(ctx, c.bucket, key, minio.GetObjectOptions{})
if err != nil {
return nil, "", err
}
stat, err := obj.Stat()
if err != nil {
obj.Close()
return nil, "", err
}
return obj, stat.ContentType, nil
}
// ListKeys returns object keys with the given prefix (used for migration).
func (c *Client) ListKeys(ctx context.Context, prefix string) ([]string, error) {
if c == nil {
return nil, fmt.Errorf("storage not configured")
}
var keys []string
for obj := range c.mc.ListObjects(ctx, c.bucket, minio.ListObjectsOptions{Prefix: prefix}) {
if obj.Err != nil {
return nil, obj.Err
}
keys = append(keys, obj.Key)
}
return keys, nil
}
// PresignedURL returns a temporary URL (not used by the app; available for admin previews).
func (c *Client) PresignedURL(ctx context.Context, key string, expiry time.Duration) (string, error) {
if c == nil {
return "", fmt.Errorf("storage not configured")
}
u, err := c.mc.PresignedGetObject(ctx, c.bucket, key, expiry, nil)
if err != nil {
return "", err
}
return u.String(), nil
}