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 使用ESP8266连接阿里云出现问题
  • ¥15 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角