dou7851 2017-04-28 14:55
浏览 37

使用HTTP请求上下文管理频道

I have a basic HTTP server that accepts a request and returns data from a data store.

Each HTTP request does the following things:

  1. Create a context with timeout
  2. Create a read request (custom type)
  3. Push read request onto channel
  4. Wait for response and serve data

Here's 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, because the context could finish at any time due to the deadline being exceeded or the client cancelling the request, is my current approach correct for handling this in multiple places or is there a more elegant solution?

  • 写回答

1条回答 默认 最新

  • douluohan3403 2017-12-08 07:15
    关注

    seems to me that it'll work. few comments -

    1. you can return in the first case of <- ctx.Done()
    2. you're already waiting for req.ctx.Done() in the data store handler so you can completely remove the first select {} statement and just publish to the data requests channel. not sure about performance hits for the rare cases when the context is done so early before the request is even published...
    评论

报告相同问题?

悬赏问题

  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统