Skip to content

Commit

Permalink
Setup http server timeout connections
Browse files Browse the repository at this point in the history
Move stopBrowserMiddleware after logging middleware,
but before timeoutMiddleware.

Set Write and Read timeouts for http server.
  • Loading branch information
miry committed Aug 28, 2022
1 parent 805fe34 commit eb7154d
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 5 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
* Replace logrus with zerolog. (#413, @miry)
* Log HTTP requests to API server. (#413, #421, @miry)
* Add TimeoutHandler for the HTTP API server. (#420, @miry)
* Set Write and Read timeouts for HTTP API server connections. (@miry)

# [2.4.0] - 2022-03-07

Expand Down
16 changes: 11 additions & 5 deletions api.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,12 +46,12 @@ func (server *ApiServer) PopulateConfig(filename string) {
}
}

func StopBrowsersMiddleware(h http.Handler) http.Handler {
func stopBrowsersMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if strings.HasPrefix(r.UserAgent(), "Mozilla/") {
http.Error(w, "User agent not allowed", 403)
} else {
h.ServeHTTP(w, r)
next.ServeHTTP(w, r)
}
})
}
Expand All @@ -74,6 +74,7 @@ func (server *ApiServer) Listen(host string, port string) {
Dur("duration", duration).
Msg("")
}))
r.Use(stopBrowsersMiddleware)
r.Use(timeoutMiddleware)

r.HandleFunc("/reset", server.ResetState).Methods("POST")
Expand All @@ -95,16 +96,21 @@ func (server *ApiServer) Listen(host string, port string) {
r.Handle("/metrics", server.Metrics.handler())
}

http.Handle("/", StopBrowsersMiddleware(r))

server.Logger.
Info().
Str("host", host).
Str("port", port).
Str("version", Version).
Msgf("Starting HTTP server on endpoint %s:%s", host, port)

err := http.ListenAndServe(net.JoinHostPort(host, port), nil)
srv := &http.Server{
Handler: r,
Addr: net.JoinHostPort(host, port),
WriteTimeout: 10 * time.Second,
ReadTimeout: 10 * time.Second,
}

err := srv.ListenAndServe()
if err != nil {
server.Logger.Fatal().Err(err).Msg("ListenAndServe finished with error")
}
Expand Down

0 comments on commit eb7154d

Please sign in to comment.