Managing channels using the context of an HTTP request

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:
            // request pushed to que
        case <-ctx.Done():
            // don't push onto reqStream if ctx done
        }

        select {
        case <-ctx.Done():
            // don't try and serve content if ctx done
        case data := <-req.data:
            // return data to client
        }

    }
}

func main() {
    dataReqs := make(chan dataRequest)
    go func() {
        for {
            select {
            case req := <-dataReqs:
                select {
                case <-req.ctx.Done():
                    // don't push onto data channel if ctx done
                case req.data <- "some data":
                    // get data from store
                }
            }
        }
    }()
    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?

+4
source share
1 answer
, . -
  • return <- ctx.Done()
  • req.ctx.Done() , select {} . , , ...
0

Source: https://habr.com/ru/post/1675924/


All Articles