Created
July 8, 2019 12:46
-
-
Save pokutuna/5637971a29f1e8010aa8fcd69bc4851f to your computer and use it in GitHub Desktop.
context
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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