package gemini import ( "context" "crypto/tls" "io" "net" "sync" ) 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, 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), handler: handler, } go s.propagateCancel() return s, nil } func (s *Server) Close() { s.cancel() s.wg.Wait() } func (s *Server) Serve() { s.wg.Add(1) defer s.wg.Done() for { conn, err := s.listener.Accept() if err != nil { return } s.wg.Add(1) go s.handleConn(conn) } } 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 } resp := s.handler(s.ctx, req) defer resp.Close() _, _ = io.Copy(conn, resp) } func (s *Server) propagateCancel() { go func() { <-s.ctx.Done() _ = s.listener.Close() }() } func (s *Server) closed() bool { select { case <-s.ctx.Done(): return true default: return false } }