cleanup static handler, add reasonable timeouts

This commit is contained in:
AJ ONeal 2020-09-28 01:55:23 -06:00
parent c768866991
commit b6f0e9bc73
1 changed files with 21 additions and 10 deletions

31
main.go
View File

@ -6,6 +6,7 @@ import (
"fmt" "fmt"
"net/http" "net/http"
"os" "os"
"time"
"git.coolaj86.com/coolaj86/goserv/assets" "git.coolaj86.com/coolaj86/goserv/assets"
"github.com/go-chi/chi" "github.com/go-chi/chi"
@ -102,28 +103,38 @@ func serve() {
r.Use(middleware.Logger) r.Use(middleware.Logger)
r.Use(middleware.Recoverer) r.Use(middleware.Recoverer)
var staticHandler http.HandlerFunc
pub := http.FileServer(assets.Assets) pub := http.FileServer(assets.Assets)
var dev http.Handler
var devFS http.FileSystem
if len(runOpts.static) > 0 { if len(runOpts.static) > 0 {
devFS = http.Dir(runOpts.static) // try the user-provided directory first, then fallback to the built-in
dev = http.FileServer(devFS) devFS := http.Dir(runOpts.static)
r.Get("/*", func(w http.ResponseWriter, r *http.Request) { dev := http.FileServer(devFS)
staticHandler = func(w http.ResponseWriter, r *http.Request) {
if _, err := devFS.Open(r.URL.Path); nil != err { if _, err := devFS.Open(r.URL.Path); nil != err {
pub.ServeHTTP(w, r) pub.ServeHTTP(w, r)
return return
} }
dev.ServeHTTP(w, r) dev.ServeHTTP(w, r)
}) }
} else { } else {
r.Get("/*", func(w http.ResponseWriter, r *http.Request) { staticHandler = func(w http.ResponseWriter, r *http.Request) {
pub.ServeHTTP(w, r) pub.ServeHTTP(w, r)
}) }
} }
fmt.Println("Listening for http on", runOpts.listen) r.Get("/*", staticHandler)
if err := http.ListenAndServe(runOpts.listen, r); nil != err {
fmt.Println("Listening for http (with reasonable timeouts) on", runOpts.listen)
srv := &http.Server{
Addr: runOpts.listen,
Handler: r,
ReadHeaderTimeout: 2 * time.Second,
ReadTimeout: 10 * time.Second,
WriteTimeout: 20 * time.Second,
MaxHeaderBytes: 1024 * 1024, // 1MiB
}
if err := srv.ListenAndServe(); nil != err {
fmt.Fprintf(os.Stderr, "%s", err) fmt.Fprintf(os.Stderr, "%s", err)
os.Exit(1) os.Exit(1)
return return