2016-06-26 11:03:15 +00:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"log"
|
|
|
|
"net/http"
|
|
|
|
"strings"
|
|
|
|
)
|
|
|
|
|
2018-09-18 20:16:58 +00:00
|
|
|
type imagesHandler struct {
|
2016-06-26 11:03:15 +00:00
|
|
|
name string
|
2018-09-18 20:16:58 +00:00
|
|
|
auth func(*http.Request) bool
|
2016-06-26 11:03:15 +00:00
|
|
|
hndlr http.Handler
|
2022-09-04 19:45:39 +00:00
|
|
|
getter func(fname string) (*Picture, error)
|
2016-06-26 11:03:15 +00:00
|
|
|
}
|
|
|
|
|
2022-09-04 19:45:39 +00:00
|
|
|
func ImagesHandler(name string, auth func(*http.Request) bool, hndlr http.Handler, getter func(fname string) (*Picture, error)) imagesHandler {
|
2016-06-26 11:03:15 +00:00
|
|
|
return imagesHandler{name, auth, hndlr, getter}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (i imagesHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
|
|
|
log.Printf("Handling %s %s request from %s: %s [%s]\n", r.Method, i.name, r.RemoteAddr, r.URL.Path, r.UserAgent())
|
|
|
|
|
|
|
|
// Don't handle subdirectories
|
|
|
|
if strings.Contains(r.URL.Path[1:], "/") {
|
|
|
|
http.Error(w, "Image not found.", http.StatusBadRequest)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// Refuse most methods
|
|
|
|
if r.Method != "GET" && r.Method != "HEAD" {
|
|
|
|
http.Error(w, "Method not allowed.", http.StatusMethodNotAllowed)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// Refuse content
|
|
|
|
if r.ContentLength != 0 {
|
|
|
|
http.Error(w, "This request doesn't accept content.", http.StatusRequestEntityTooLarge)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// Check rights
|
2018-09-18 20:16:58 +00:00
|
|
|
if !i.auth(r) {
|
2016-06-26 11:03:15 +00:00
|
|
|
w.Header().Set("WWW-Authenticate", "Basic realm=\"YouP0m\"")
|
|
|
|
http.Error(w, "You are not allowed to perform this request.", http.StatusUnauthorized)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// Search the picture
|
|
|
|
if pict, err := i.getter(r.URL.Path[1:]); err != nil {
|
|
|
|
http.Error(w, err.Error(), http.StatusNotFound)
|
|
|
|
return
|
|
|
|
} else {
|
2022-09-04 19:45:39 +00:00
|
|
|
r.URL.Path = "/" + pict.path
|
2016-06-26 11:03:15 +00:00
|
|
|
i.hndlr.ServeHTTP(w, r)
|
|
|
|
}
|
|
|
|
}
|