Go net/http 服务器错误:accept tcp [::]:443:accept4:打开文件太多;重试

发布于 2025-01-12 18:32:08 字数 2004 浏览 0 评论 0原文

这是我的服务器:

package main

import (
        "my-project/pkg/configuration"
        "my-project/pkg/logger"
        "my-project/pkg/server/appConfig"
        "my-project/pkg/server/handlers"
        "net/http"
        "os"
        "strings"
)

func main() {

        if len(os.Args) < 2 {
                logger.Log("error", "main", "Missing config.json file path as argument")
                return
        }

        configuration := configuration.Configuration{}
        appConfig.InitConfig(os.Args[1], &configuration)

        // download file
        http.HandleFunc("/file-download", handlers.DownloadFile(&configuration))

        // upload file
        http.HandleFunc("/file-upload", handlers.UploadFile(&configuration))

        // Get url
        http.HandleFunc("/file-url", handlers.GetUrl(&configuration))

        // Delete
        http.HandleFunc("/delete", handlers.DeleteHandler(&configuration))

        // file system
        fs := http.FileServer(http.Dir(configuration.RootStoragePath))
        corsFS := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
                if strings.HasSuffix(r.URL.Path, "/") {
                        http.NotFound(w, r)
                        return
                }
                w.Header().Add("Access-Control-Allow-Origin", "*")
                fs.ServeHTTP(w, r)
        })

        http.Handle("/", corsFS)

        err := http.ListenAndServeTLS(":443", "crt/server.crt", "crt/server.key", nil)
        if err != nil {
                logger.Log("error", "ListenAndServeTLS", err.Error())
        }
}

服务器负载中等。 服务器运行一天后崩溃了, 我收到以下错误:

http: Accept error: accept tcp [::]:443: accept4: too many open files; retrying

命令:

ls -ltr /proc/{PROCESS_ID}/fd

文件列表和套接字:[XXXXXX] 一直在增长。 我不想更改 ulimit (1024),我不认为这是一个长期修复...

我真的不明白问题可能来自哪里...在处理程序中,我操作文件,但我注意延迟 Close()... 我必须设置超时吗?如果是的话在哪里?

预先感谢您的所有帮助...

Here is my server :

package main

import (
        "my-project/pkg/configuration"
        "my-project/pkg/logger"
        "my-project/pkg/server/appConfig"
        "my-project/pkg/server/handlers"
        "net/http"
        "os"
        "strings"
)

func main() {

        if len(os.Args) < 2 {
                logger.Log("error", "main", "Missing config.json file path as argument")
                return
        }

        configuration := configuration.Configuration{}
        appConfig.InitConfig(os.Args[1], &configuration)

        // download file
        http.HandleFunc("/file-download", handlers.DownloadFile(&configuration))

        // upload file
        http.HandleFunc("/file-upload", handlers.UploadFile(&configuration))

        // Get url
        http.HandleFunc("/file-url", handlers.GetUrl(&configuration))

        // Delete
        http.HandleFunc("/delete", handlers.DeleteHandler(&configuration))

        // file system
        fs := http.FileServer(http.Dir(configuration.RootStoragePath))
        corsFS := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
                if strings.HasSuffix(r.URL.Path, "/") {
                        http.NotFound(w, r)
                        return
                }
                w.Header().Add("Access-Control-Allow-Origin", "*")
                fs.ServeHTTP(w, r)
        })

        http.Handle("/", corsFS)

        err := http.ListenAndServeTLS(":443", "crt/server.crt", "crt/server.key", nil)
        if err != nil {
                logger.Log("error", "ListenAndServeTLS", err.Error())
        }
}

The server is under medium load.
The server crashed after a day of running,
I got the following error:

http: Accept error: accept tcp [::]:443: accept4: too many open files; retrying

The command :

ls -ltr /proc/{PROCESS_ID}/fd

And the list of file, and socket:[XXXXXX] is growing all the time.
I don't want to change ulimit (1024), I don't think it is a long terme fix...

I don't really see where the problem could come from... In the handlers, I manipulate files but I take care to do defer Close()...
Do I have to set timeouts? If so where?

Thank you in advance for all the help ...

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

青萝楚歌 2025-01-19 18:32:08

我终于找到了解决方案。

事实上,net/http 包的 http.ListenAndServe 方法默认没有超时。这是 Go 团队自愿的。因此,对于生产中的服务,有必要声明一个 http.Server{} 并配置它。 Go 文档
来源:Cloudflare 博客文章

        srv := &http.Server{
                Addr:         ":443",
                ReadTimeout:  30 * time.Second,
                WriteTimeout: 120 * time.Second,
        }   
        srv.SetKeepAlivesEnabled(false)

        err := srv.ListenAndServeTLS("crt/server.crt", "crt/server.key")

http.DefaultServeMux 是默认的请求多路复用器,HandleFuncDefaultServeMux 中注册给定模式的处理函数。
这是实现:

func main() {

        if len(os.Args) < 2 { 
                logger.Log("error", "main", "Missing config.json file path as argument")
                return
        }

        configuration := configuration.Configuration{}
        appConfig.InitConfig(os.Args[1], &configuration)

        // download file
        http.HandleFunc("/file-download", handlers.DownloadFile(&configuration))

        // upload file
        http.HandleFunc("/file-upload", handlers.UploadFile(&configuration))

        // Get url
        http.HandleFunc("/file-url", handlers.GetUrl(&configuration))

        // Delete
        http.HandleFunc("/delete", handlers.DeleteHandler(&configuration))

        // file system
        fs := http.FileServer(http.Dir(configuration.RootStoragePath))
        corsFS := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
                if strings.HasSuffix(r.URL.Path, "/") {
                        http.NotFound(w, r)
                        return
                }   
                w.Header().Add("Access-Control-Allow-Origin", "*")
                fs.ServeHTTP(w, r)
        })

        http.Handle("/", corsFS)

        srv := &http.Server{
                Addr:         ":443",
                ReadTimeout:  30 * time.Second,
                WriteTimeout: 120 * time.Second,
        }   
        srv.SetKeepAlivesEnabled(false)

        err := srv.ListenAndServeTLS("crt/server.crt", "crt/server.key")
        if err != nil {
                logger.Log("error", "ListenAndServeTLS", err.Error())
                os.Exit(1)
        }
}

如果您有任何其他建议,我显然很感兴趣。

I finally managed to find a solution.

The fact is that the http.ListenAndServe method of the net/http package has no timeout by default. This is voluntary from the Go team. So for a service in production, it is necessary to declare a http.Server{} and to configure it. Go doc.
Source : Cloudflare blog post

        srv := &http.Server{
                Addr:         ":443",
                ReadTimeout:  30 * time.Second,
                WriteTimeout: 120 * time.Second,
        }   
        srv.SetKeepAlivesEnabled(false)

        err := srv.ListenAndServeTLS("crt/server.crt", "crt/server.key")

http.DefaultServeMux is the default request multiplexer, and HandleFunc registers the handler function for the given pattern in the DefaultServeMux.
Here is the implementation :

func main() {

        if len(os.Args) < 2 { 
                logger.Log("error", "main", "Missing config.json file path as argument")
                return
        }

        configuration := configuration.Configuration{}
        appConfig.InitConfig(os.Args[1], &configuration)

        // download file
        http.HandleFunc("/file-download", handlers.DownloadFile(&configuration))

        // upload file
        http.HandleFunc("/file-upload", handlers.UploadFile(&configuration))

        // Get url
        http.HandleFunc("/file-url", handlers.GetUrl(&configuration))

        // Delete
        http.HandleFunc("/delete", handlers.DeleteHandler(&configuration))

        // file system
        fs := http.FileServer(http.Dir(configuration.RootStoragePath))
        corsFS := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
                if strings.HasSuffix(r.URL.Path, "/") {
                        http.NotFound(w, r)
                        return
                }   
                w.Header().Add("Access-Control-Allow-Origin", "*")
                fs.ServeHTTP(w, r)
        })

        http.Handle("/", corsFS)

        srv := &http.Server{
                Addr:         ":443",
                ReadTimeout:  30 * time.Second,
                WriteTimeout: 120 * time.Second,
        }   
        srv.SetKeepAlivesEnabled(false)

        err := srv.ListenAndServeTLS("crt/server.crt", "crt/server.key")
        if err != nil {
                logger.Log("error", "ListenAndServeTLS", err.Error())
                os.Exit(1)
        }
}

If you have any other advice, I'm obviously interested.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文