webfs/cmd/webfs/main.go

77 lines
1.7 KiB
Go

package main
import (
"bytes"
"context"
"flag"
"fmt"
"github.com/bakape/thumbnailer"
"golang.org/x/net/webdav"
"log"
"net/http"
"os"
"path"
"path/filepath"
"strconv"
)
type Handler struct {
webdav.Handler
}
func (h *Handler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
width, _ := strconv.Atoi(req.FormValue("w"))
height, _ := strconv.Atoi(req.FormValue("h"))
if (width > 0) || (height > 0) {
h.ServeThumbnail(w, req, uint(width), uint(height))
return
}
h.Handler.ServeHTTP(w, req)
}
func (h *Handler) ServeThumbnail(w http.ResponseWriter, req *http.Request, width uint, height uint) {
srcPath := path.Clean(req.URL.Path)
srcFile, err := h.FileSystem.OpenFile(context.Background(), srcPath, os.O_RDONLY, 0664)
if err != nil {
http.NotFound(w, req)
return
}
defer srcFile.Close()
srcFileInfo, err := srcFile.Stat()
if err != nil {
http.NotFound(w, req)
return
}
var opts thumbnailer.Options
opts.ThumbDims.Width = width
opts.ThumbDims.Height = height
_, thumb, err := thumbnailer.Process(srcFile, opts)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
ext := "jpeg"
if thumb.IsPNG {
ext = "png"
}
fileName := filepath.Base(srcPath)
thumbFileName := fmt.Sprintf("%s.thumb.%s", fileName, ext)
thumbRs := bytes.NewReader(thumb.Image.Data)
http.ServeContent(w, req, thumbFileName, srcFileInfo.ModTime(), thumbRs)
}
func main() {
address := flag.String("a", "localhost:8080", "Address to listen to.")
flag.Parse()
handler := &Handler{}
handler.FileSystem = webdav.Dir(".")
handler.LockSystem = webdav.NewMemLS()
log.Println("Listening on", *address)
http.ListenAndServe(*address, handler)
}