From 96f3a7607ffbdb349a4c2eff35efdf11b8d35a4e Mon Sep 17 00:00:00 2001 From: tjpcc Date: Tue, 10 Jan 2023 13:46:35 -0700 Subject: Add a CGI contrib --- gemini/serve.go | 52 ++++++++++++++++++++++++++++++++++++++++++++-------- 1 file changed, 44 insertions(+), 8 deletions(-) (limited to 'gemini/serve.go') diff --git a/gemini/serve.go b/gemini/serve.go index d439472..8fd6b57 100644 --- a/gemini/serve.go +++ b/gemini/serve.go @@ -10,17 +10,33 @@ import ( type Server struct { ctx context.Context + network string + address string cancel context.CancelFunc wg *sync.WaitGroup listener net.Listener handler Handler } -func NewServer(ctx context.Context, tlsConfig *tls.Config, listener net.Listener, handler Handler) *Server { +func NewServer( + ctx context.Context, + tlsConfig *tls.Config, + network string, + address string, + handler Handler, +) (*Server, error) { ctx, cancel := context.WithCancel(ctx) + listener, err := net.Listen(network, address) + if err != nil { + cancel() + return nil, err + } + s := &Server{ ctx: ctx, + network: network, + address: address, cancel: cancel, wg: &sync.WaitGroup{}, listener: tls.NewListener(listener, tlsConfig), @@ -28,7 +44,7 @@ func NewServer(ctx context.Context, tlsConfig *tls.Config, listener net.Listener } go s.propagateCancel() - return s + return s, nil } func (s *Server) Close() { @@ -51,22 +67,42 @@ func (s *Server) Serve() { } } +func (s *Server) Network() string { + return s.network +} + +func (s *Server) Address() string { + return s.address +} + +func (s *Server) Hostname() string { + host, _, _ := net.SplitHostPort(s.address) + return host +} + +func (s *Server) Port() string { + _, portStr, _ := net.SplitHostPort(s.address) + return portStr +} + func (s *Server) handleConn(conn net.Conn) { defer s.wg.Done() defer conn.Close() req, err := ParseRequest(conn) + if err != nil { + _, _ = io.Copy(conn, BadRequest(err.Error())) + return + } + + req.Server = s + req.RemoteAddr = conn.RemoteAddr() if tlsconn, ok := conn.(*tls.Conn); req != nil && ok { state := tlsconn.ConnectionState() req.TLSState = &state } - var resp *Response - if err == nil { - resp = s.handler(s.ctx, req) - } else { - resp = BadRequest(err.Error()) - } + resp := s.handler(s.ctx, req) defer resp.Close() _, _ = io.Copy(conn, resp) -- cgit v1.2.3