Skip to content

Commit

Permalink
add some timeouts, have a panic handler
Browse files Browse the repository at this point in the history
  • Loading branch information
quii committed Mar 3, 2020
1 parent ffb48c3 commit 30ae249
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 2 deletions.
2 changes: 1 addition & 1 deletion Dockerfile
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
FROM alpine:3.9.4

RUN apk add --update wget bash ca-certificates && \
wget -O mockingjay-server https://github.com/quii/mockingjay-server/releases/download/1.11.3/linux_amd64_mockingjay-server --no-check-certificate && \
wget -O mockingjay-server https://github.com/quii/mockingjay-server/releases/download/1.11.4/linux_amd64_mockingjay-server --no-check-certificate && \
chmod +x mockingjay-server && \
apk del wget bash && \
rm -rf /var/cache/apk/*
Expand Down
30 changes: 29 additions & 1 deletion main.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"fmt"
"log"
"net/http"
"time"
)

func main() {
Expand All @@ -24,11 +25,38 @@ func main() {
log.Fatal(err)
} else {
config.logger.Printf("Listening on port %d", config.port)
err = http.ListenAndServe(fmt.Sprintf(":%d", config.port), svr)
webServer := newServer(svr, config.port)
err = webServer.ListenAndServe()
if err != nil {
msg := fmt.Sprintf("There was a problem starting the mockingjay server on port %d: %s", config.port, err.Error())
config.logger.Fatal(msg)
}
}
}
}

func newServer(router http.Handler, port int) *http.Server {
return &http.Server{
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
IdleTimeout: 30 * time.Second,
ReadHeaderTimeout: 20 * time.Second,
Handler: http.TimeoutHandler(Recovery(router), 5*time.Second, "Timed out!"),
Addr: fmt.Sprintf(":%d", port),
}
}

func Recovery(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer func() {
err := recover()
if err != nil {
msg := fmt.Sprintf("Oh dear, mockingjay has had a panic %#v", err)
log.Println(msg)
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprint(w, msg)
}
}()
next.ServeHTTP(w, r)
})
}

0 comments on commit 30ae249

Please sign in to comment.