context: realistic usage of context.

Use a go routine for the work logic. Here sleep and append to string.
Inside the go routine, select for ctx.Done(). If happens, just stop and
return.

In the outside function, select for ctx.Done() too. If it happens, that
means the work logic has not finished before canceled.
This commit is contained in:
2024-09-21 20:35:43 +02:00
parent c0db9ab22b
commit c5582275e7
2 changed files with 45 additions and 59 deletions

View File

@ -1,30 +1,18 @@
package context
import (
"context"
"fmt"
"net/http"
)
type Store interface {
Fetch() string
Cancel()
Fetch(ctx context.Context) (string, error)
}
func Server(store Store) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
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()
}
data, _ := store.Fetch(r.Context())
fmt.Fprint(w, data)
}
}