Skip to content

Instantly share code, notes, and snippets.

@kaneshin
Created October 27, 2017 12:48
Show Gist options
  • Save kaneshin/e8716225622839992eac8c5cd2f49530 to your computer and use it in GitHub Desktop.
Save kaneshin/e8716225622839992eac8c5cd2f49530 to your computer and use it in GitHub Desktop.
package main
import (
"context"
"log"
"net/http"
"time"
)
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
// `requestTimeout' でこのリクエストはタイムアウト(処理を全て終わらせる)
const requestTimeout = 100 * time.Millisecond
ctx, cancel := context.WithTimeout(r.Context(), requestTimeout)
defer cancel()
// タイムアウトを設定したコンテキストをリクエストに再度設定
r = r.WithContext(ctx)
// goroutine
go func(parent context.Context) {
const timeout = 500 * time.Millisecond
ctx, cancel := context.WithTimeout(parent, timeout)
defer cancel()
select {
case <-ctx.Done():
log.Print("goroutine done")
}
}(ctx)
const timeout = 800 * time.Millisecond
select {
case <-ctx.Done():
log.Print("done")
case <-time.After(timeout):
log.Print("timeout")
}
})
http.ListenAndServe(":8080", nil)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment