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

@@ -38,6 +38,18 @@ if err := application.RunWith(ctx, server, ":8080"); err != nil {
`omni.New()` 默认仍使用 `transport/nethttp` 路由;native 服务端是显式启用的预览实现,等协议和连接边界稳定后再考虑切换默认启动器。
TLS 可以直接作为 `App.RunWith` 的启动配置:
```go
server := native.New(nil)
server.TLSConfig = &tls.Config{Certificates: certificates}
if err := application.RunWith(ctx, server, ":8443"); err != nil {
log.Fatal(err)
}
```
需要自己持有 listener 或配置证书文件时,分别使用 `ServeTLS` 或 `RunTLS`;TLS 握手仍受 native 的读超时、连接上限和优雅关闭控制。
## 可移植路由规则(v0.3.0)
| 项目 | 约定 |

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 {

View File

@@ -3,9 +3,17 @@ package native_test
import (
"bufio"
"context"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/tls"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"errors"
"fmt"
"io"
"math/big"
"net"
"net/http"
"strings"
@@ -848,6 +856,96 @@ func TestAppRunWithNativeRunner(t *testing.T) {
}
}
func TestAppRunWithNativeTLS(t *testing.T) {
application := omni.NewWithRouter(netrouter.New())
application.GET("/health", func(ctx *omni.Context) error { return ctx.OK("ok") })
certificate := testCertificate(t)
server := native.New(nil)
server.TLSConfig = &tls.Config{
Certificates: []tls.Certificate{certificate},
MinVersion: tls.VersionTLS12,
}
address := freeAddress(t)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
done := make(chan error, 1)
go func() { done <- application.RunWith(ctx, server, address) }()
client := &http.Client{Transport: &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, // test certificate is self-signed
}}
defer client.CloseIdleConnections()
var response *http.Response
var err error
deadline := time.Now().Add(2 * time.Second)
for response == nil && time.Now().Before(deadline) {
response, err = client.Get("https://" + address + "/health")
if err != nil {
time.Sleep(10 * time.Millisecond)
}
}
if err != nil || response == nil {
t.Fatalf("TLS request failed: response=%v error=%v", response, err)
}
body, readErr := io.ReadAll(response.Body)
response.Body.Close()
if readErr != nil || response.StatusCode != http.StatusOK || !strings.Contains(string(body), `"data":"ok"`) {
t.Fatalf("unexpected TLS response: status=%d body=%q error=%v", response.StatusCode, body, readErr)
}
cancel()
select {
case err := <-done:
if err != nil {
t.Fatal(err)
}
case <-time.After(3 * time.Second):
t.Fatal("TLS RunWith did not stop")
}
}
func testCertificate(t *testing.T) tls.Certificate {
t.Helper()
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
t.Fatal(err)
}
serial, err := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 120))
if err != nil {
t.Fatal(err)
}
now := time.Now()
template := &x509.Certificate{
SerialNumber: serial,
Subject: pkix.Name{CommonName: "localhost"},
NotBefore: now.Add(-time.Minute),
NotAfter: now.Add(time.Hour),
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
DNSNames: []string{"localhost"},
}
der, err := x509.CreateCertificate(rand.Reader, template, template, &key.PublicKey, key)
if err != nil {
t.Fatal(err)
}
certificate, err := tls.X509KeyPair(
pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der}),
pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: mustMarshalECKey(t, key)}),
)
if err != nil {
t.Fatal(err)
}
return certificate
}
func mustMarshalECKey(t *testing.T, key *ecdsa.PrivateKey) []byte {
t.Helper()
der, err := x509.MarshalECPrivateKey(key)
if err != nil {
t.Fatal(err)
}
return der
}
func startServer(t *testing.T, handler http.Handler) (*native.Server, net.Listener, <-chan error) {
t.Helper()
listener, err := net.Listen("tcp", "127.0.0.1:0")