Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Setup http server timeout connections #423

Merged
merged 1 commit into from Aug 28, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
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
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