net/http
's ListenAndServe
function has no support for setting timeouts GO-S211440 fmt.Println("Server is running on port 9090") // Print Server is running on port 9090
41 go out.Ellipsis("Server is running") // Print Server is running with ellipsis
42
43 err := http.ListenAndServe(port, nil) // Start web server on port 9090 // If error return err44
45 if err != nil { // If error
46 log.Fatal("Error starting server: ", err) // If error panic and stop program
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)
}
}