go-by-test/context/context.go
vinchent c5582275e7 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.
2024-09-21 20:35:43 +02:00

19 lines
293 B
Go

package context
import (
"context"
"fmt"
"net/http"
)
type Store interface {
Fetch(ctx context.Context) (string, error)
}
func Server(store Store) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
data, _ := store.Fetch(r.Context())
fmt.Fprint(w, data)
}
}