响应后如何关闭连接(使用UNIX套接字)

时间:2019-01-05 07:25:00

标签: go

一些响应后,套接字保持连接状态并泄漏fd。

...
unix  2      [ ]         STREAM     CONNECTED     30973530 /tmp/cfs
unix  2      [ ]         STREAM     CONNECTED     30972715 /tmp/cfs
unix  3      [ ]         STREAM     CONNECTED     31023652 /tmp/cfs
...

每个响应后如何强制关闭连接?

package main

import (
    "log"
    "net"
    "net/http"
    "os"
    "sync"
    "syscall"
)

type Server struct {
    net.Listener
    socketPath string
    isClosed   bool
    sync.Mutex
}

func StartServer(socketPath string, mux *http.ServeMux) (server *Server, err error) {
    if listener, err := newListener(socketPath); err == nil {
        server = &Server{listener, socketPath, false, sync.Mutex{}}
        go func() {
            if err := http.Serve(server, mux); err != nil && !server.IsClosed() {
                log.Print("ERROR unable to serve: ", err)
            }
        }()
        log.Println("Server listening to " + socketPath)
    }
    return
}

func (this *Server) IsClosed() bool {
    return this.isClosed
}

func newListener(socketPath string) (listener net.Listener, err error) {
    os.Remove(socketPath)
    syscall.Umask(0000)
    listener, err = net.Listen("unix", socketPath)
    listener.Addr()
    return
}

0 个答案:

没有答案