Closed. This question is opinion-based。它当前不接受答案。












想改善这个问题吗?更新问题,以便editing this post用事实和引用来回答。

12天前关闭。



Improve this question




为什么http.ServeMux没有像这样的Remove方法:
// Remove url from m, Regularization is not considered
func (mux *ServeMux) Remove(url string) {
    mux.mu.Lock()
    defer mux.mu.Unlock()
    delete(mux.m, url)
}

最佳答案

除了路由ServeMux之外,map还有更多的功能。
source中,有一个按长度排序的所有路由es slice -确定了路由优先级:

type ServeMux struct {
    mu    sync.RWMutex
    m     map[string]muxEntry
    es    []muxEntry // slice of entries sorted from longest to shortest.
    hosts bool       // whether any patterns contain hostnames
}
如果要分叉自己的ServeMux,则在删除路由时需要更新es

很难想到实际需要动态删除路由。即使已实施,ServeMux仍将“处理”已删除的路由-返回404(未找到)状态错误。
如果要禁用路由,则将这种动态逻辑放入处理程序本身,直接返回404-或401(未经授权)或403(禁止)-看起来更简单,更自然。

关于go - 为什么http.ServeMux没有Remove方法? ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/63911895/

10-13 05:10