dqg17080 2018-11-18 08:12 采纳率: 0%
浏览 36

通过通道处理HTTP请求的模式

I am writing a web application where I have a long running goroutine. I want to delegate all HTTP requests to this goroutine via channels. The pattern that I have come across is:

// Internal long running goroutine
for{
  select{
  case e := <-event: //web request
    req := e.req
    // do something
    ....
    select {
    case <-ctx.Done():
       //log  
    default: 
      e.replyTo <- result
    }
  }
}

// Web handler
http.HandleFunc("/bar", func(w http.ResponseWriter, r *http.Request) {
  //decode request etc
  ...

  replyTo := make(chan interface{}, 1)
  ctx, cancel := context.WithCancel(context.BackGround())
  event <- Event{req: req, ctx: ctx, replyTo: replyTo}
  select{
  case <-time.After(time.Second):
     cancel()
     //return 500
  case r := <-replyTo:
    // return some response
  }
})

I do see that there is one single go-routine at the end, so parallelism is lost but I am okay with it.

Is this pattern the right way of doing this? What other approaches can be suggested?

  • 写回答

1条回答 默认 最新

  • duanluan3651 2018-11-18 09:16
    关注

    Is this pattern the right way of doing this?

    Assuming you are trying to manage where state in a single go routine, I would say no. I think it would be better to have some form of a state manager that is responsible for thread safety. Therefore the handler should take in something that can manage the state and simply expose a few methods to the handler.

    type State interface{
      Load() (string, error)
      Save(something string) error
    }
    

    Decoupling the code will pay off for you later on. It will also allow unit tests for both the handler and the State that can be focused and readable.

    评论

报告相同问题?

悬赏问题

  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 MATLAB中streamslice问题
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 51单片机中C语言怎么做到下面类似的功能的函数(相关搜索:c语言)
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序