github.com/volts-dev/volts@v0.0.0-20240120094013-5e9c65924106/transport/http_server.go (about)

     1  package transport
     2  
     3  import (
     4  	"net"
     5  	"net/http"
     6  
     7  	"golang.org/x/net/http2"
     8  	"golang.org/x/net/http2/h2c"
     9  )
    10  
    11  type (
    12  	customHandler interface {
    13  		//ServeHTTP(ResponseWriter, *Request)
    14  		ServeHTTP(w http.ResponseWriter, r *THttpRequest)
    15  	}
    16  	customxx struct {
    17  		hd customHandler
    18  	}
    19  	httpTransportListener struct {
    20  		listener  net.Listener
    21  		transport *HttpTransport
    22  		sock      *HttpConn // TODO 还没实现
    23  		http      *http.Server
    24  	}
    25  )
    26  
    27  func (self *customxx) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    28  	self.hd.ServeHTTP(w, NewHttpRequest(r))
    29  }
    30  
    31  func (h *httpTransportListener) Addr() net.Addr {
    32  	return h.listener.Addr()
    33  }
    34  
    35  func (h *httpTransportListener) Close() error {
    36  	err := h.http.Close()
    37  	if err != nil {
    38  		return err
    39  	}
    40  	return h.listener.Close()
    41  }
    42  
    43  func (t *httpTransportListener) Accept() (net.Conn, error) {
    44  	return t.listener.Accept()
    45  }
    46  
    47  func (h *httpTransportListener) Serve(handler Handler) error {
    48  	if hd, ok := handler.Handler().(http.Handler); ok {
    49  		h.http = &http.Server{
    50  			Handler: hd,
    51  		}
    52  	}
    53  
    54  	if hd, ok := handler.Handler().(customHandler); ok {
    55  		h.http = &http.Server{
    56  			Handler: &customxx{
    57  				hd: hd,
    58  			},
    59  		}
    60  	}
    61  	// default http2 server
    62  
    63  	// insecure connection use h2c
    64  	if !(h.transport.config.Secure || h.transport.config.TlsConfig != nil) {
    65  		h.http.Handler = h2c.NewHandler(h.http.Handler, &http2.Server{})
    66  	}
    67  
    68  	// begin serving
    69  	return h.http.Serve(h.listener)
    70  }
    71  
    72  func (self *httpTransportListener) Sock() ISocket {
    73  	return self.sock
    74  }