I have a basic HTTP server that accepts a request and returns data from a data store.
Each HTTP request performs the following actions:
- Create timeout context
- Create a read request (custom type)
- Click read request on channel
- Wait for a response and complete the data
Here is the basic pseudo code:
package main
import (
"context"
"net/http"
"time"
)
type dataRequest struct {
data chan string
ctx context.Context
}
func handler(reqStream chan dataRequest) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second)
defer cancel()
req := dataRequest{
data: make(chan string),
ctx: ctx,
}
select {
case reqStream <- req:
case <-ctx.Done():
}
select {
case <-ctx.Done():
case data := <-req.data:
}
}
}
func main() {
dataReqs := make(chan dataRequest)
go func() {
for {
select {
case req := <-dataReqs:
select {
case <-req.ctx.Done():
case req.data <- "some data":
}
}
}
}()
http.HandleFunc("/", handler(dataReqs))
http.ListenAndServe(":8080", nil)
}
My question is, can the context end at any time due to exceeding the deadline or cancel the client’s request, is my current approach suitable for processing this in several places or is there a more elegant solution?
source
share