forked from Terry-Mao/gopush2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
net.go
53 lines (46 loc) · 1.04 KB
/
net.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package main
import (
"fmt"
"net"
"net/http"
)
type KeepAliveListener struct {
net.Listener
}
func (l *KeepAliveListener) Accept() (c net.Conn, err error) {
c, err = l.Listener.Accept()
if err != nil {
Log.Printf("Listener.Accept() failed (%s)", err.Error())
return
}
// set keepalive
if tc, ok := c.(*net.TCPConn); !ok {
panic("Assection type failed c.(net.TCPConn)")
} else {
err = tc.SetKeepAlive(true)
if err != nil {
Log.Printf("tc.SetKeepAlive(true) failed (%s)", err.Error())
return
}
}
return
}
func Listen(addr string, port int) error {
a := fmt.Sprintf("%s:%d", addr, port)
if Conf.TCPKeepAlive == 1 {
server := &http.Server{}
l, err := net.Listen("tcp", a)
if err != nil {
Log.Printf("net.Listen(\"tcp\", \"%s\") failed (%s)", a, err.Error())
return err
}
return server.Serve(&KeepAliveListener{Listener: l})
} else {
if err := http.ListenAndServe(a, nil); err != nil {
Log.Printf("http.ListenAdServe(\"%s\") failed (%s)", a, err.Error())
return err
}
}
// nerve here
return nil
}