github.com/chwjbn/xclash@v0.2.0/listener/http/server.go (about) 1 package http 2 3 import ( 4 "net" 5 "time" 6 7 "github.com/chwjbn/xclash/common/cache" 8 C "github.com/chwjbn/xclash/constant" 9 ) 10 11 type Listener struct { 12 listener net.Listener 13 addr string 14 closed bool 15 relay bool 16 } 17 18 // RawAddress implements C.Listener 19 func (l *Listener) RawAddress() string { 20 return l.addr 21 } 22 23 // Address implements C.Listener 24 func (l *Listener) Address() string { 25 return l.listener.Addr().String() 26 } 27 28 // Close implements C.Listener 29 func (l *Listener) Close() error { 30 l.closed = true 31 return l.listener.Close() 32 } 33 34 func (l *Listener) SetRelay(relay bool) { 35 l.relay=true 36 } 37 38 func New(addr string, in chan<- C.ConnContext) (*Listener, error) { 39 return NewWithAuthenticate(addr, in, true) 40 } 41 42 func NewWithAuthenticate(addr string, in chan<- C.ConnContext, authenticate bool) (*Listener, error) { 43 l, err := net.Listen("tcp", addr) 44 if err != nil { 45 return nil, err 46 } 47 48 var c *cache.Cache 49 if authenticate { 50 c = cache.New(time.Second * 30) 51 } 52 53 hl := &Listener{ 54 listener: l, 55 addr: addr, 56 relay: false, 57 } 58 go func() { 59 for { 60 conn, err := hl.listener.Accept() 61 if err != nil { 62 if hl.closed { 63 break 64 } 65 continue 66 } 67 go HandleConn(conn, in, c) 68 } 69 }() 70 71 return hl, nil 72 }