Source file src/net/http/http3.go

     1  // Copyright 2026 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package http
     6  
     7  import (
     8  	"context"
     9  	"crypto/tls"
    10  	"net"
    11  )
    12  
    13  // http3Server is an HTTP/3 server implementation.
    14  // x/net/http3 registers an implementation of this interface by passing it to Server.Serve.
    15  type http3Server interface {
    16  	ServeHTTP3(context.Context, net.PacketConn, *tls.Config, Handler) error
    17  	Shutdown(ctx context.Context) error
    18  }
    19  
    20  func (s *Server) setHTTP3Server(h3 http3Server) {
    21  	if s.h3Server != nil {
    22  		panic("http: HTTP/3 Server already registered")
    23  	}
    24  	s.h3Server = h3
    25  }
    26  
    27  // http3PacketConn is a net.Listener we pass to Server.BaseContext for HTTP/3 ports.
    28  type http3PacketConn struct {
    29  	conn net.PacketConn
    30  }
    31  
    32  func (c http3PacketConn) Accept() (net.Conn, error) { return nil, net.ErrClosed }
    33  func (c http3PacketConn) Close() error              { return c.conn.Close() }
    34  func (c http3PacketConn) Addr() net.Addr            { return c.conn.LocalAddr() }
    35  
    36  func (s *Server) serveHTTP3(conn net.PacketConn, certFile, keyFile string) error {
    37  	baseCtx := context.Background()
    38  	if s.BaseContext != nil {
    39  		// The Server.BaseContext hook receives a net.Listener.
    40  		// For HTTP/3 connections, provide it with a Listener that has the same Addr
    41  		// as the PacketConn we're actually serving from.
    42  		baseCtx = s.BaseContext(http3PacketConn{conn})
    43  	}
    44  	baseCtx = context.WithValue(baseCtx, ServerContextKey, s)
    45  
    46  	tlsConfig, err := s.setupTLSConfig(certFile, keyFile, []string{"h3"})
    47  	if err != nil {
    48  		return err
    49  	}
    50  	return s.h3Server.ServeHTTP3(baseCtx, conn, tlsConfig, serverHandler{s})
    51  }
    52  

View as plain text