doufei9946 2018-10-26 00:46
浏览 37
已采纳

固定Golang goroutine或频道以请求/响应

From what I know, the default http router as well as the gorilla/mux router put each incoming HTTP request entrypoint on its own goroutine. Like Node.js domains, where we can pin a request to a domain, can we pin a request in Golang to a goroutine, and if there is any panic in the goroutine, we respond with an error instead of shutting down the server?

In node.js, it might look like:

const domain = require('domain');
const http = require('http');

const server = http.createServer((req,res) => {

  const d = domain.create();

  d.once('error', e =>{
     res.json({error:e}); // check res.headersSent to see if already sent
  });

  res.once('finish', () => {
     d.removeAllListeners(); // prevent memory leak
  });

  d.run(() => {
     handleRequest(req,res);
  });


});

is there a way to do something similar with goroutines in Golang?

  • 写回答

2条回答 默认 最新

  • douxiajia6104 2018-10-26 01:10
    关注

    Yes, you can recover from a goroutine panics. This middleware from gorilla does it but it is also easy to do yourself. It's basically just wrapping your handler in a function that defers calling recover() and handling the panic from there.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?