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:
@ -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)
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user