apps/shrink/handlers.go 1.5 K raw
1
package main
2
3
import (
4
	"io"
5
	"net/http"
6
	"strconv"
7
8
	"github.com/stevedylandev/andromeda/pkg/web"
9
)
10
11
const maxUploadBytes = 20 * 1024 * 1024
12
13
func (a *App) indexHandler(w http.ResponseWriter, r *http.Request) {
14
	web.Render(a.Templates, w, "index.html", nil, a.Log)
15
}
16
17
func (a *App) compressHandler(w http.ResponseWriter, r *http.Request) {
18
	r.Body = http.MaxBytesReader(w, r.Body, maxUploadBytes)
19
	if err := r.ParseMultipartForm(maxUploadBytes); err != nil {
20
		http.Error(w, "Failed to read upload: "+err.Error(), http.StatusBadRequest)
21
		return
22
	}
23
24
	file, header, err := r.FormFile("file")
25
	if err != nil {
26
		http.Error(w, "No file provided", http.StatusBadRequest)
27
		return
28
	}
29
	defer file.Close()
30
	data, err := io.ReadAll(file)
31
	if err != nil {
32
		http.Error(w, "Failed to read file: "+err.Error(), http.StatusBadRequest)
33
		return
34
	}
35
36
	quality := 80
37
	if v := r.FormValue("quality"); v != "" {
38
		if q, err := strconv.Atoi(v); err == nil {
39
			quality = q
40
		}
41
	}
42
	width := 0
43
	if v := r.FormValue("width"); v != "" {
44
		if wv, err := strconv.Atoi(v); err == nil && wv > 0 {
45
			width = wv
46
		}
47
	}
48
49
	out, err := compressImage(data, quality, width)
50
	if err != nil {
51
		http.Error(w, "Compression failed: "+err.Error(), http.StatusInternalServerError)
52
		return
53
	}
54
55
	name := "image"
56
	if header != nil && header.Filename != "" {
57
		name = header.Filename
58
	}
59
	w.Header().Set("Content-Type", "image/jpeg")
60
	w.Header().Set("Content-Disposition", `attachment; filename="`+buildDownloadFilename(name, "jpg")+`"`)
61
	_, _ = w.Write(out)
62
}