github.com/c2FmZQ/websocket is a fork of gorilla/websocket that adds server-side support for:
- WebSocket over HTTP/2 (RFC 8441 Extended
CONNECT, including cleartexth2c) - WebSocket over HTTP/3 (RFC 9220 Extended
CONNECT, compatible withquic-go/http3)
Upgrader.Upgrade returns a concrete *websocket.Conn across HTTP/1.1, HTTP/2, and HTTP/3, preserving drop-in API compatibility with gorilla/websocket—including subprotocol negotiation, permessage-deflate compression (RFC 7692), PreparedMessage, WriteBufferPool, and JSON helpers—with no additional runtime dependencies.
go get github.com/c2FmZQ/websocket
-
Enabling Extended
CONNECTin Go'snet/http(HTTP/2): Go's standard librarynet/httpserver disables RFC 8441 (SETTINGS_ENABLE_CONNECT_PROTOCOL) by default starting in Go 1.24.-
Go 1.28+ (
golang/go@e29e95265674, go.dev/issue/53208): Enable ExtendedCONNECTper server viahttp.HTTP2Config.EnableConnectProtocol(not yet in a released Go version as of Go 1.27):srv := &http.Server{ Handler: mux, HTTP2: &http.HTTP2Config{ EnableConnectProtocol: true, }, }
-
Go 1.24–1.27:
HTTP2Config.EnableConnectProtocolis not yet available, andhttp2xconnectcannot be set via//go:debug. SetGODEBUG=http2xconnect=1in the environment at process startup, or import theh2xconnecthelper package before any package that importsnet/http:import ( _ "github.com/c2FmZQ/websocket/h2xconnect" )
(
quic-go/http3.ServeradvertisesSETTINGS_ENABLE_CONNECT_PROTOCOL = 1by default.) -
-
Route registration: HTTP/1.1 WebSocket handshakes use
GET, whereas HTTP/2 and HTTP/3 ExtendedCONNECThandshakes useCONNECT. When using method-specifichttp.ServeMuxpatterns, register both:mux.HandleFunc("GET /ws", handleWS) mux.HandleFunc("CONNECT /ws", handleWS)
-
Handler lifetime (differs from
gorilla/websocket): Over HTTP/2 and HTTP/3, the underlying stream is tied to the lifetime ofhttp.Handler.ServeHTTP. The common gorilla pattern of starting read/write goroutines and returning from the handler does not work. KeepServeHTTPactive for the duration of the WebSocket session and close the connection before returning.Upgrader.Servedoes both:func handleWS(w http.ResponseWriter, r *http.Request) { upgrader.Serve(w, r, nil, func(conn *websocket.Conn) { // Read/write using conn. The connection is closed when this returns. }) }
After
Closereturns, the connection's methods returnnet.ErrClosed, so goroutines that still hold it are safe. Returning from the handler without callingClosewhile another goroutine uses the connection is a data race with the HTTP server. -
Middleware: Any middleware that wraps
http.ResponseWritermust implementUnwrap() http.ResponseWriterso thathttp.ResponseControllercan reach the stream's deadlines and flushing. Without deadlines, a peer could block the connection forever, soUpgraderejects HTTP/2 and HTTP/3 requests with500 Internal Server Errorwhen they are unavailable.
BSD-2-Clause (see LICENSE).