context: setup timeout context

This commit is contained in:
2024-09-21 20:20:15 +02:00
parent d49f952035
commit 0b181ccf0f
2 changed files with 65 additions and 14 deletions

View File

@ -7,10 +7,24 @@ import (
type Store interface {
Fetch() string
Cancel()
}
func Server(store Store) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, store.Fetch())
ctx := r.Context()
data := make(chan string, 1)
go func() {
data <- store.Fetch()
}()
select {
case d := <-data:
fmt.Fprint(w, d)
case <-ctx.Done():
store.Cancel()
}
}
}