github.com/volts-dev/volts@v0.0.0-20240120094013-5e9c65924106/transport/listener.go (about) 1 package transport 2 3 import ( 4 "context" 5 "net" 6 "net/http" 7 "time" 8 9 "golang.org/x/net/http2" 10 "golang.org/x/net/http2/h2c" 11 ) 12 13 type ( 14 transportListener struct { 15 listener net.Listener 16 transport ITransport 17 sock ISocket // TODO 还没实现 18 http *http.Server 19 } 20 ) 21 22 func (self *transportListener) Addr() net.Addr { 23 return self.listener.Addr() 24 } 25 26 func (self *transportListener) Close() error { 27 if self.http != nil { 28 err := self.http.Close() 29 if err != nil { 30 return err 31 } 32 } 33 34 return self.listener.Close() 35 } 36 37 func (t *transportListener) Accept() (net.Conn, error) { 38 return t.listener.Accept() 39 } 40 41 func (self *transportListener) Serve(handler Handler) error { 42 switch v := handler.Handler().(type) { 43 case http.Handler: 44 self.http = &http.Server{ 45 Handler: v, 46 } 47 // default http2 server 48 49 // insecure connection use h2c 50 if !(self.transport.Config().Secure || self.transport.Config().TlsConfig != nil) { 51 self.http.Handler = h2c.NewHandler(self.http.Handler, &http2.Server{}) 52 } 53 54 // begin serving 55 return self.http.Serve(self.listener) 56 57 case customHandler: 58 self.http = &http.Server{ 59 Handler: &customxx{ 60 hd: v, 61 }, 62 } 63 // default http2 server 64 65 // insecure connection use h2c 66 if !(self.transport.Config().Secure || self.transport.Config().TlsConfig != nil) { 67 self.http.Handler = h2c.NewHandler(self.http.Handler, &http2.Server{}) 68 } 69 70 // begin serving 71 return self.http.Serve(self.listener) 72 73 case rpcHandler: 74 var tempDelay time.Duration 75 76 for { 77 conn, err := self.listener.Accept() 78 if err != nil { 79 if ne, ok := err.(net.Error); ok && ne.Temporary() { 80 if tempDelay == 0 { 81 tempDelay = 5 * time.Millisecond 82 } else { 83 tempDelay *= 2 84 } 85 if max := 1 * time.Second; tempDelay > max { 86 tempDelay = max 87 } 88 log.Errf("http: Accept error: %v; retrying in %v\n", err, tempDelay) 89 time.Sleep(tempDelay) 90 continue 91 } 92 return err 93 } 94 95 sock := NewTcpTransportSocket(conn, self.transport.Config().ReadTimeout, self.transport.Config().WriteTimeout) 96 go func() { 97 //@ 获取空白通讯包 98 msg := GetMessageFromPool() // request message 99 100 // TODO: think of a better error response strategy 101 defer func() { 102 if r := recover(); r != nil { 103 sock.Close() 104 } 105 106 PutMessageToPool(msg) 107 }() 108 109 // TODO 自定义通讯包结构 110 // 获得请求参数 111 err = msg.Decode(conn) // 等待读取客户端信号 112 if err != nil { 113 //return err 114 // TODO 115 } 116 117 ctx := context.WithValue(context.Background(), RemoteConnContextKey, conn) 118 119 req := NewRpcRequest(ctx, msg, sock) 120 rsp := NewRpcResponse(ctx, req, sock) 121 122 v.ServeRPC(rsp, req) 123 }() 124 } 125 } 126 127 return nil 128 } 129 130 func (self *transportListener) Sock() ISocket { 131 return self.sock 132 }