doumeinuoye81969 2014-03-12 13:40
浏览 3
已采纳

如何在Go中禁用HTTP警报

I have a problem with the following error when calling http.ListenAndServe:

http: Accept error: *ip* accept tcp too many open files; retrying in 10ms

How I can disable this? ulimit -n is 1024 and I can't change it.

  • 写回答

2条回答 默认 最新

  • doujiao9426 2014-03-12 14:55
    关注

    The problem is that you cannot open anymore file descriptors and therefore you cannot accept more connections. If you can't change the fact you have three possible options to deal with this problem:

    1. Leave it as it is: The standard library uses an exponential backoff to wait for a time when there are file descriptors again. This is generally a good practice and gives future clients a chance to get a slot. In fact, the http package does this for every temporary network error that occurs.
    2. Close the connection when a temporary error like this occurs. This can be achieved by wrapping the net.Listener returned by net.Listen and modify it's Accept() method to drop the connection on temporary errors.
    3. Ignore the message. If the message is the only thing that bothers you, you can simply set the log.Output() to ioutil.Discard. (While this is an option, I don't see the use of that. You will end up ignoring important error messages and wonder why your service does not work.)

    I would prefer the first but there may be a case where you want the second, so here is an example of a connection dropping listener (on play):

    type DroppingListener struct {
        net.Listener
    }
    
    func (d DroppingListener) Accept() (net.Conn, error) {
        for {
            conn, err := d.Listener.Accept()
    
            if err != nil {
                if ne, ok := err.(net.Error); ok && ne.Temporary() {
                    log.Println("Dropping connection because:", ne)
                    continue
                }
            }
    
            return conn, err
        }
    }
    
    func ListenAndServe(addr string, handler http.Handler) error {
        srv := &http.Server{Addr: addr, Handler: handler}
    
        l, e := net.Listen("tcp", addr)
        if e != nil {
            return e
        }
    
        l = &DroppingListener{l}
    
        return srv.Serve(l)
    }
    

    With this DroppingListener, the Accept method will return a connection as soon as there is no more temporary error.

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

报告相同问题?

悬赏问题

  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化