net/http
's ListenAndServe
function has no support for setting timeouts GO-S211438}
39
40func MuxListen(path string, port int, mux *http.ServeMux) error {
41 return http.ListenAndServe(path+":"+strconv.Itoa(port), mux)42}
43
44func MuxListenTLS(path string, port int, cert string, key string, mux *http.ServeMux) error {
42}
43
44func MuxListenTLS(path string, port int, cert string, key string, mux *http.ServeMux) error {
45 return http.ListenAndServeTLS(path+":"+strconv.Itoa(port), cert, key, mux)46}
HTTP timeouts are necessary to expire inactive connections and failing to do so might make the application vulnerable to attacks like slowloris which work by sending data very slow, which in case of no timeout will keep the connection active eventually leading to a denial-of-service (DoS) attack.
package main
import (
"fmt"
"time"
"net/http"
)
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, %s!", r.URL.Path[1:])
})
err := http.ListenAndServe(":1234", nil)
if err != nil {
panic(err)
}
}
package main
import (
"fmt"
"time"
"net/http"
)
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, %s!", r.URL.Path[1:])
})
server := &http.Server{
Addr: ":1234",
ReadHeaderTimeout: 3 * time.Second,
}
err := server.ListenAndServe()
if err != nil {
panic(err)
}
}