douzang7928 2013-04-10 03:03 采纳率: 100%
浏览 25
已采纳

如何退订HTTP处理程序?

I want to create http handler to handle one session:

func init(){
    http.HandleFunc("/sess/215489598", func(w http.ResponseWriter, r *http.Request) {
        //do something
    })
}

and then remove it when session ends(expires).

How can I do that ?

  • 写回答

2条回答 默认 最新

  • doucai6663 2013-04-10 05:03
    关注

    This isn't directly possible: an HTTP multiplexer (type ServeMux) does not expose a deletion operation.

    Using an HTTP multiplexer for session management turns out to be a bad idea. The current implementation of HTTP serving is kind of inefficient. It scans the entire multiplexer table for each URL, so the more handlers you have, the worse performance gets. That's fine for a few paths, but you can't manage even a few hundred sessions that way, much less hundreds of thousands.

    The HTTP multiplexer would need some kind of synchronization to be used as a session management tool. Imagine there was an Unhandle method. If you Unhandle a path, you would expect the multiplexer to no longer handle your path with its previous data. But, different goroutines aren't guaranteed to see each other's changes to the same data without some kind of synchronization. So, the HTTP handler could still see the old view of the multiplexer, then respond to the request using the handler you thought you deregistered.

    So, the HTTP handler itself can't do this for you- nor should it, because you don't have any means to synchronize your session lifespan.

    Create a single handler for "/sess/". That handler should be responsible for delegating to individual sessions. It can use a map[sessionID]sessionHandler to do this efficiently, and can either pipe all session management over channels to let a single goroutine keep track of sessions being created and destroyed, or go with a more traditional approach using reader-writer locks around your session map. This way, you can ensure that you won't try to dispatch a new request to a session handler after you've removed it.

    Of course, you can get an HTTP request at any time, so someone might jump in and connect to a session the moment before you lock the map to delete the session, if a context switch happens in the instruction after you have decided you want to lock the map but before you actually do it, so manage your locks and session policies carefully. The "right thing" to do here depends mostly on the needs of your individual application.

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

报告相同问题?

悬赏问题

  • ¥15 正弦信号发生器串并联电路电阻无法保持同步怎么办
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 个人网站被恶意大量访问,怎么办
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序