Created
October 27, 2017 12:48
-
-
Save kaneshin/e8716225622839992eac8c5cd2f49530 to your computer and use it in GitHub Desktop.
This file contains 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 ( | |
"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