Skip to content

Instantly share code, notes, and snippets.

@ianfoo
Last active November 10, 2019 10:34
Show Gist options
  • Select an option

  • Save ianfoo/f78885a24090d01507a64ca2bbf2d3b9 to your computer and use it in GitHub Desktop.

Select an option

Save ianfoo/f78885a24090d01507a64ca2bbf2d3b9 to your computer and use it in GitHub Desktop.
Simple Go HTTP server with write timeout
ianbook%
ianbook% http -h :3030 s==50
HTTP/1.1 200 OK
Content-Length: 0
Date: Sun, 10 Nov 2019 10:33:32 GMT
ianbook% http -h :3030 s==200
http: error: ConnectionError: ('Connection aborted.', RemoteDisconnected('Remote end closed connection without response')) while doing GET request to URL: http://localhost:3030/?s=200
ianbook% http -h :3030 s==20
HTTP/1.1 200 OK
Content-Length: 0
Date: Sun, 10 Nov 2019 10:33:51 GMT
ianbook%
ianbook% go run /tmp/timeout.go -timeout 100
2019/11/10 02:33:16 serving at :3030 with 100 ms timeout
2019/11/10 02:33:32 request: sleeping for 50ms
2019/11/10 02:33:32 finished sleeping
2019/11/10 02:33:44 request: sleeping for 200ms
2019/11/10 02:33:45 finished sleeping
2019/11/10 02:33:51 request: sleeping for 20ms
2019/11/10 02:33:51 finished sleeping
package main
import (
"flag"
"fmt"
"log"
"net/http"
"strconv"
"strings"
"time"
)
var (
addr = flag.String("addr", ":3030", "Address to bind server to")
timeout = flag.Uint("timeout", 500, "Milliseconds for write timeout")
)
func main() {
flag.Parse()
if strings.Index(*addr, ":") == -1 {
*addr = ":" + *addr
}
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
sleepParam := r.URL.Query().Get("s")
if sleepParam == "" {
sleepParam = "100"
}
sleep, err := strconv.Atoi(sleepParam)
if err != nil {
http.Error(
w,
fmt.Errorf("bad sleep param: %w", err).Error(),
http.StatusBadRequest)
return
}
log.Printf("request: sleeping for %dms", sleep)
time.Sleep(time.Duration(sleep) * time.Millisecond)
log.Print("finished sleeping")
})
srv := &http.Server{
Addr: *addr,
WriteTimeout: time.Duration(*timeout) * time.Millisecond,
}
log.Printf("serving at %s with %d ms timeout", *addr, *timeout)
log.Fatal(srv.ListenAndServe())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment