feat: add native TLS serving

This commit is contained in:
2026-09-21 04:44:47 +08:00
parent 4daf3b211c
commit 847621d218
6 changed files with 160 additions and 2 deletions

View File

@@ -10,6 +10,7 @@ import (
"bufio"
"bytes"
"context"
"crypto/tls"
"errors"
"io"
"net"
@@ -48,6 +49,9 @@ type Server struct {
MaxBodyBytes int64
MaxConnections int
MaxConcurrentRequests int
// TLSConfig enables TLS for Run and App.RunWith. ServeTLS can be used
// when the listener and TLS configuration are assembled by the caller.
TLSConfig *tls.Config
mu sync.Mutex
handler http.Handler
@@ -115,9 +119,52 @@ func (s *Server) Run(ctx context.Context, handler http.Handler, address string)
if err != nil {
return err
}
if s.TLSConfig != nil {
return s.ServeTLS(ctx, listener, s.TLSConfig)
}
return s.Serve(ctx, listener)
}
// RunTLS loads a certificate pair, listens on address and serves native HTTP
// over TLS. The server still owns the listener and follows the same shutdown
// and connection-limit rules as Run.
func (s *Server) RunTLS(ctx context.Context, handler http.Handler, address, certFile, keyFile string) error {
if handler != nil {
s.handler = handler
}
if s.handler == nil {
return errors.New("go-omni/native: nil handler")
}
if address == "" {
address = ":8443"
}
certificate, err := tls.LoadX509KeyPair(certFile, keyFile)
if err != nil {
return err
}
listener, err := net.Listen("tcp", address)
if err != nil {
return err
}
return s.ServeTLS(ctx, listener, &tls.Config{
Certificates: []tls.Certificate{certificate},
MinVersion: tls.VersionTLS12,
})
}
// ServeTLS wraps listener with a TLS listener and serves native HTTP. The
// caller owns the TLS configuration value; it must contain a certificate or
// a certificate callback accepted by crypto/tls.
func (s *Server) ServeTLS(ctx context.Context, listener net.Listener, config *tls.Config) error {
if listener == nil {
return errors.New("go-omni/native: nil listener")
}
if config == nil {
return errors.New("go-omni/native: nil TLS config")
}
return s.Serve(ctx, tls.NewListener(listener, config))
}
// Serve accepts connections from listener until the context is canceled or an
// unrecoverable accept error occurs. The listener is owned by the Server.
func (s *Server) Serve(ctx context.Context, listener net.Listener) error {