image-transformer/main.go

174 lines
4.3 KiB
Go
Raw Normal View History

// (c) 2018 Karthik Karanth (https://github.com/medakk/gotiny)
// (c) 2018-2021 Andreas Neue <an@dnix.de>
2019-01-08 23:05:20 +00:00
package main
import (
"flag"
2019-01-08 23:05:20 +00:00
"fmt"
"io"
2019-01-08 23:05:20 +00:00
"log"
"net/http"
"strconv"
"strings"
"github.com/davidbyttow/govips/v2/vips"
2019-01-08 23:05:20 +00:00
)
var (
2019-07-31 05:06:38 +00:00
imgServer = flag.String("s", "https://images.example.com/", "URL prefix")
listenAddr = flag.String("l", "0.0.0.0:8080", "Listen address")
sizesFilter = flag.String("f", "", "Allowed sizes")
)
func init() {
flag.Parse()
}
func transform(w http.ResponseWriter, r *http.Request) {
2019-01-08 23:05:20 +00:00
// Get the query parameters from the request URL
path := r.URL.EscapedPath()
parm := strings.Split(path, "/")
2019-01-13 20:09:53 +00:00
if len(parm) < 4 {
writeError(w, "", "", "error in arguments", http.StatusBadRequest)
2019-01-08 23:05:20 +00:00
return
}
2019-01-13 20:09:53 +00:00
method := parm[1]
args := parm[2]
imgPath := strings.Join(parm[3:], "/")
2019-01-08 23:05:20 +00:00
// Start fetching the image from the given url
2019-01-13 20:09:53 +00:00
resp, err := http.Get(*imgServer + imgPath)
2019-01-08 23:05:20 +00:00
if err != nil {
2019-01-13 20:09:53 +00:00
writeError(w, imgPath, method, "failed to fetch image", http.StatusNotFound)
2019-01-08 23:05:20 +00:00
return
}
defer resp.Body.Close()
// Ensure that a valid response was given
if resp.StatusCode/100 != 2 {
writeError(w, imgPath, method, fmt.Sprintf("failed to fetch image (%v)", resp.StatusCode), http.StatusBadRequest)
return
}
buf := []byte{}
errMsg := ""
2021-05-22 18:58:57 +00:00
errCode := 0
2019-01-08 23:05:20 +00:00
2019-01-13 20:09:53 +00:00
switch method {
case "pass":
break
2021-05-22 18:58:57 +00:00
2019-01-13 20:09:53 +00:00
case "resize":
buf, errMsg, errCode = doResize(resp.Body, args)
if buf == nil {
writeError(w, imgPath, method, errMsg, errCode)
2019-07-31 05:06:38 +00:00
}
2021-05-22 18:58:57 +00:00
case "blur":
buf, errMsg, errCode = doBlur(resp.Body, args)
if buf == nil {
writeError(w, imgPath, method, errMsg, errCode)
}
2019-01-08 23:05:20 +00:00
default:
writeError(w, imgPath, method, "unknown method", http.StatusBadRequest)
return
}
2019-01-13 20:09:53 +00:00
_, err = w.Write(buf)
if err != nil {
writeError(w, imgPath, method, fmt.Sprintf("%v", err), http.StatusInternalServerError)
return
}
}
2019-01-13 20:09:53 +00:00
func doResize(body io.ReadCloser, args string) ([]byte, string, int) {
allowed := strings.Split(*sizesFilter, ",")
forbidden := true
if allowed[0] == "*" {
forbidden = false
} else {
for _, v := range allowed {
if args == v {
forbidden = false
break
}
2019-01-13 20:09:53 +00:00
}
}
if forbidden {
return nil, "size is not allowed", http.StatusForbidden
}
2019-01-13 20:09:53 +00:00
size := strings.Split(args, "x")
if len(size) < 2 {
return nil, "width and height are required", http.StatusBadRequest
}
width := size[0]
height := size[1]
2019-01-13 20:09:53 +00:00
// Validate that all three required fields are present
if width == "" || height == "" {
return nil, "width and height are required", http.StatusBadRequest
}
// Convert width and height to integers
iw, errW := strconv.Atoi(width)
ih, errH := strconv.Atoi(height)
if errW != nil || errH != nil {
return nil, "width and height must be integers", http.StatusBadRequest
2019-01-08 23:05:20 +00:00
}
2019-01-13 20:09:53 +00:00
// Read from response body, convert and write to output buffer
img, err := vips.NewImageFromReader(body)
if err != nil {
return nil, fmt.Sprintf("%v", err), http.StatusInternalServerError
}
err = img.Thumbnail(iw, ih, 0)
if err != nil {
return nil, fmt.Sprintf("%v", err), http.StatusInternalServerError
}
ep := vips.NewDefaultExportParams() // default export params are sufficient
buf, _, _ := img.Export(ep)
if err != nil {
return nil, fmt.Sprintf("%v", err), http.StatusInternalServerError
}
return buf, "", 0
2019-01-13 20:09:53 +00:00
}
2021-05-22 18:58:57 +00:00
func doBlur(body io.ReadCloser, args string) ([]byte, string, int) {
// Convert width and heigh to integers
sigma, err := strconv.ParseFloat(args, 64)
if err != nil {
return nil, "invalid sigma", http.StatusInternalServerError
}
img, err := vips.NewImageFromReader(body)
if err != nil {
return nil, fmt.Sprintf("%v", err), http.StatusInternalServerError
}
err = img.GaussianBlur(sigma)
if err != nil {
return nil, fmt.Sprintf("%v", err), http.StatusInternalServerError
}
ep := vips.NewDefaultExportParams() // default export params are sufficient
buf, _, _ := img.Export(ep)
if err != nil {
return nil, fmt.Sprintf("%v", err), http.StatusInternalServerError
}
return buf, "", 0
}
2019-01-13 20:09:53 +00:00
func writeError(w http.ResponseWriter, imgPath, method, err string, status int) {
w.WriteHeader(status)
w.Write([]byte(fmt.Sprintf("Error [%s %s]: %s", method, imgPath, err)))
}
func main() {
// Start vips with the default configuration
vips.Startup(nil)
defer vips.Shutdown()
http.HandleFunc("/", transform)
2019-01-13 20:09:53 +00:00
log.Fatal(http.ListenAndServe(*listenAddr, nil))
2019-01-08 23:05:20 +00:00
}