revert to stable go-pgz/rest, switch size limiter to local implementation #71

This commit is contained in:
Umputun
2021-05-14 16:17:52 -05:00
parent 137cf692c4
commit aee7e8a57e
6 changed files with 28 additions and 49 deletions

View File

@@ -44,7 +44,7 @@ linters:
- varcheck
- stylecheck
- gochecknoinits
- exportloopref
- scopelint
- gocritic
- nakedret
- gosimple

View File

@@ -2,8 +2,6 @@ package rest
import (
"fmt"
"io"
"io/ioutil"
"net/http"
"os"
"path/filepath"
@@ -14,8 +12,7 @@ import (
// prevents directory listing.
// - public defines base path of the url, i.e. for http://example.com/static/* it should be /static
// - local for the local path to the root of the served directory
// - notFound is the reader for the custom 404 html, can be nil for default
func FileServer(public, local string, notFound io.Reader) (http.Handler, error) {
func FileServer(public, local string) (http.Handler, error) {
root, err := filepath.Abs(local)
if err != nil {
@@ -25,8 +22,7 @@ func FileServer(public, local string, notFound io.Reader) (http.Handler, error)
return nil, fmt.Errorf("local path %s doesn't exist: %w", root, err)
}
fs := http.StripPrefix(public, http.FileServer(noDirListingFS{http.Dir(root)}))
return custom404Handler(fs, notFound)
return http.StripPrefix(public, http.FileServer(noDirListingFS{http.Dir(root)})), nil
}
type noDirListingFS struct{ fs http.FileSystem }
@@ -51,38 +47,3 @@ func (fs noDirListingFS) Open(name string) (http.File, error) {
}
return f, nil
}
// respWriter404 intercept Write to provide custom 404 response
type respWriter404 struct {
http.ResponseWriter
status int
msg []byte
}
func (w *respWriter404) WriteHeader(status int) {
w.status = status
w.ResponseWriter.WriteHeader(status)
}
func (w *respWriter404) Write(p []byte) (n int, err error) {
if w.status != http.StatusNotFound || w.msg == nil {
return w.ResponseWriter.Write(p)
}
_, err = w.ResponseWriter.Write(w.msg)
return len(p), err
}
func custom404Handler(next http.Handler, notFound io.Reader) (http.Handler, error) {
if notFound == nil {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { next.ServeHTTP(w, r) }), nil
}
body, err := ioutil.ReadAll(notFound)
if err != nil {
return nil, err
}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
next.ServeHTTP(&respWriter404{ResponseWriter: w, msg: body}, r)
}), nil
}

View File

@@ -26,8 +26,6 @@ func SizeLimit(size int64) func(http.Handler) http.Handler {
w.WriteHeader(http.StatusServiceUnavailable)
return
}
_ = r.Body.Close() // the original body already consumed
if int64(len(content)) > size {
w.WriteHeader(http.StatusRequestEntityTooLarge)
return