From 7e28d79fbd7506ce0064cb97d05dfd47f397edd4 Mon Sep 17 00:00:00 2001 From: Anders Pearson Date: Fri, 17 Feb 2017 21:47:48 +0000 Subject: [PATCH] set read/write timeouts on http server Go's http.Server can be configured with read/write timeouts: https://golang.org/pkg/net/http/#Server that's a good idea to make it a bit more robust against bad clients. put some reasonable defaults of 5/10 seconds but they can also be overridden with environment variables. --- hound.go | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/hound.go b/hound.go index 2c10cb7..a03a5e6 100644 --- a/hound.go +++ b/hound.go @@ -58,6 +58,8 @@ type config struct { SMTPUser string `envconfig:"SMTP_USER"` SMTPPassword string `envconfig:"SMTP_PASSWORD"` LogLevel string `envconfig:"LOG_LEVEL"` + ReadTimeout int `envconfig:"READ_TIMEOUT"` + WriteTimeout int `envconfig:"WRITE_TIMEOUT"` } func main() { @@ -114,6 +116,14 @@ func main() { SMTP_USER = c.SMTPUser SMTP_PASSWORD = c.SMTPPassword + // some defaults + if c.ReadTimeout == 0 { + c.ReadTimeout = 5 + } + if c.WriteTimeout == 0 { + c.WriteTimeout = 10 + } + LAST_ERROR_EMAIL = time.Now() go func() { @@ -166,6 +176,10 @@ func main() { } t.Execute(w, pr) }) - - log.Fatal(http.ListenAndServe(":"+c.HTTPPort, nil)) + s := &http.Server{ + Addr: ":" + c.HTTPPort, + ReadTimeout: time.Duration(c.ReadTimeout) * time.Second, + WriteTimeout: time.Duration(c.WriteTimeout) * time.Second, + } + log.Fatal(s.ListenAndServe()) }