Skip to main content

Overview

The h2c middleware enables HTTP/2 cleartext (h2c) connections, allowing HTTP/2 over unencrypted connections for development and internal services. Use it when you need:
  • HTTP/2 without TLS
  • Development HTTP/2 testing
  • Internal service communication

Installation

Quick Start

Examples

Basic H2C Server

With Custom Server

API Reference

Functions

Technical Details

Implementation Overview

The h2c middleware provides HTTP/2 cleartext support through two main mechanisms:
  1. HTTP/2 Prior Knowledge: Direct HTTP/2 connections where the client knows in advance that the server supports HTTP/2. Detected by checking ProtoMajor == 2.
  2. HTTP/2 Upgrade: HTTP/1.1 upgrade mechanism using the h2c upgrade protocol (RFC 7540, Section 3.2).

Core Components

Options Configuration

  • AllowUpgrade (default: true): Enables HTTP/1.1 to HTTP/2 upgrade requests
  • AllowDirect (default: true): Enables direct HTTP/2 connections with prior knowledge
  • OnUpgrade: Optional callback function triggered when an upgrade occurs

Context Information

The middleware stores connection information in the request context:

Upgrade Detection

The middleware validates h2c upgrade requests by checking:
  • Connection header contains β€œUpgrade” token
  • Upgrade header equals β€œh2c” (case-insensitive)
  • HTTP2-Settings header is present

Connection Handling

  • Uses http.Hijacker interface to take over the TCP connection
  • Sends 101 Switching Protocols response
  • Manages connection lifecycle with buffered reading via BufferedConn

Helper Functions

  • GetInfo(c *mizu.Ctx): Retrieves h2c information from context
  • IsHTTP2(c *mizu.Ctx): Quick check if request is HTTP/2
  • ParseSettings(r *http.Request): Decodes base64-encoded HTTP2-Settings header
  • IsHTTP2Preface(data []byte): Validates HTTP/2 connection preface bytes

Security Warning

H2C transmits data unencrypted. Only use for:
  • Development environments
  • Internal services behind TLS termination
  • Testing scenarios

Best Practices

  • Never use h2c in production over public networks
  • Use behind TLS-terminating load balancer
  • Test with curl --http2-prior-knowledge

Testing

The h2c middleware includes comprehensive test coverage for all functionality: