package gemini import ( "context" "crypto/tls" "io" "net" "sync" "tildegit.org/tjp/gus" ) type server struct { ctx context.Context network string address string cancel context.CancelFunc wg *sync.WaitGroup listener net.Listener handler gus.Handler } // NewServer builds a gemini server. func NewServer( ctx context.Context, tlsConfig *tls.Config, network string, address string, handler gus.Handler, ) (gus.Server, error) { listener, err := net.Listen(network, address) if err != nil { return nil, err } addr := listener.Addr() s := &server{ ctx: ctx, network: addr.Network(), address: addr.String(), wg: &sync.WaitGroup{}, listener: tls.NewListener(listener, tlsConfig), handler: handler, } return s, nil } // Serve starts the server and blocks until it is closed. // // This function will allocate resources which are not cleaned up until // Close() is called. // // It will respect cancellation of the context the server was created with, // but be aware that Close() must still be called in that case to avoid // dangling goroutines. func (s *server) Serve() error { s.wg.Add(1) defer s.wg.Done() s.ctx, s.cancel = context.WithCancel(s.ctx) s.wg.Add(1) s.propagateCancel() for { conn, err := s.listener.Accept() if err != nil { if s.Closed() { err = nil } return err } s.wg.Add(1) go s.handleConn(conn) } } func (s *server) Close() { s.cancel() s.wg.Wait() } 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() var response *gus.Response req, err := ParseRequest(conn) if err != nil { response = BadRequest(err.Error()) return } else { req.Server = s req.RemoteAddr = conn.RemoteAddr() if tlsconn, ok := conn.(*tls.Conn); req != nil && ok { state := tlsconn.ConnectionState() req.TLSState = &state } response = s.handler(s.ctx, req) if response == nil { response = NotFound("Resource does not exist.") } defer response.Close() } _, _ = io.Copy(conn, NewResponseReader(response)) } func (s *server) propagateCancel() { go func() { defer s.wg.Done() <-s.ctx.Done() _ = s.listener.Close() }() } func (s *server) Closed() bool { select { case <-s.ctx.Done(): return true default: return false } }