go-by-test/context/context.go

31 lines
398 B
Go
Raw Normal View History

2024-09-21 18:07:09 +00:00
package context
import (
"fmt"
"net/http"
)
type Store interface {
Fetch() string
2024-09-21 18:20:15 +00:00
Cancel()
2024-09-21 18:07:09 +00:00
}
func Server(store Store) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
2024-09-21 18:20:15 +00:00
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()
}
2024-09-21 18:07:09 +00:00
}
}