Skip to content

Instantly share code, notes, and snippets.

@pokutuna
Created July 8, 2019 12:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pokutuna/5637971a29f1e8010aa8fcd69bc4851f to your computer and use it in GitHub Desktop.
Save pokutuna/5637971a29f1e8010aa8fcd69bc4851f to your computer and use it in GitHub Desktop.
context
package main
import (
"fmt"
"net/http"
"strconv"
"time"
)
type handler struct{}
func (h *handler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
fmt.Printf("%s %s\n", req.Method, req.URL)
t, err := strconv.Atoi(req.URL.Query().Get("t"))
if err != nil {
t = 5
}
ch := make(chan error, 1)
ctx := req.Context()
go func() {
time.Sleep(time.Duration(t) * time.Second)
fmt.Printf("%+v\n", "done")
ch <- nil
}()
w.WriteHeader(http.StatusOK)
select {
case <-ch:
w.Write([]byte((fmt.Sprintf("%d seconds sleeped", t))))
fmt.Printf("%+v\n", "sleeped")
case <-ctx.Done():
w.Write([]byte("cancelled" + ctx.Err().Error()))
fmt.Printf("cancelled %+v\n", ctx.Err())
}
return
}
func main() {
s := &http.Server{
Addr: ":8080",
ReadTimeout: 3 * time.Second,
WriteTimeout: 3 * time.Second,
ReadHeaderTimeout: 3 * time.Second,
Handler: &handler{},
// Handler: http.TimeoutHandler(&handler{}, 3*time.Second, "request timed out"),
}
s.ListenAndServe()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment