Skip to content

context_en.md

maoxiaoyue edited this page May 14, 2026 · 1 revision

Context Package (pkg/context)

The context package is the core of the HypGo framework, providing a consistent context wrapper across protocols (HTTP/1.1, HTTP/2, HTTP/3). Through it, you can access request information, generate responses in various formats (JSON, XML, HTML, etc.), and pass state between middleware.

Key Features

  • Standard Library Compatible: Provides methods to wrap HypGo's *Context into context.Context or extract it. Ideal for calling third-party libraries that require the standard context.Context outside the framework.
  • Unified Response Interface: Provides convenient methods such as JSON(), XML(), String(), HTML(), and File() to output content in different formats.
  • Built-in Content Negotiation: Negotiate() automatically determines whether to respond with JSON, XML, HTML, or other suitable formats based on the client's Accept header.
  • Object Pooling: Context, ResponseWriter, RequestMetrics, Params, Buffer, URLValues all use sync.Pool management, significantly reducing GC pressure.
  • Middleware Support: Provides Next(), Abort(), AbortWithStatus() and other flow control methods, making it easy to build onion-like middleware.
  • QUIC / HTTP/3 Metrics Extraction: For HTTP/3 connections, RTT (Round Trip Time) and underlying connection information can be obtained directly through Context.

Basic Usage

Use hypcontext.Context in a Controller:

package user

import (
	"net/http"

	hypcontext "github.com/maoxiaoyue/hypgo/pkg/context"
)

func GetUser(c *hypcontext.Context) {
	// Get variable from URL (e.g. /user/:id)
	id := c.Param("id")

	// Get info from query parameter (e.g. ?lang=zh)
	lang := c.DefaultQuery("lang", "en")

	// Pass value in context (usable by Middleware)
	c.Set("user_id", id)

	// Return JSON
	c.JSON(http.StatusOK, map[string]interface{}{
		"id":   id,
		"lang": lang,
		"status": "active",
	})
}

Middleware Control

Use Next() and Abort() to control request flow:

func AuthMiddleware(c *hypcontext.Context) {
	token := c.GetHeader("Authorization")
	if token == "" {
		c.AbortWithStatusJSON(http.StatusUnauthorized, map[string]string{
			"error": "Missing token",
		})
		return // Must return to stop current func execution
	}

	// Continue to the next handler
	c.Next()
}

Using in Goroutines

If you need to access Context content in another goroutine, remember to call c.Copy() to create a copy, since the original Context is returned to the object pool and cleared when the request ends.

func AsyncProcess(c *hypcontext.Context) {
	// Create a read-only copy
	cCopy := c.Copy()

	go func() {
		// Only use cCopy in this goroutine, never the original c
		DoSomething(cCopy.Request.URL.Path)
	}()

	c.String(200, "Background task started")
}

GC Optimization Strategy

The Context package employs multiple GC optimizations targeting high QPS scenarios (>100k req/s) to reduce pause times:

Map Rebuild Instead of Individual Delete

Context.reset() uses make(map[...], 8) to rebuild maps instead of deleting keys one by one. Individual deletes trigger N hash operations and GC write barriers, while rebuild produces only one allocation with the old map collected by GC as a whole:

// Before optimization: N deletes per request
for k := range c.Keys { delete(c.Keys, k) }

// After optimization: 1 make, old map collected as a whole by GC
c.Keys = make(map[string]interface{}, 8)

queryCache and formCache are set to nil directly, with lazy initialization.

Params Pool

Route parameters Params have a dedicated sync.Pool, avoiding per-request slice allocation:

// Get from pool (zero allocation)
params := hypcontext.AcquireParams(3)
defer hypcontext.ReleaseParams(params)

Router's makeContextParams() already uses this pool internally.

Object Pool List

Pool Object Capacity Limit
contextPool *Context Unlimited
responseWriterPool *responseWriter Unlimited
metricsPool *RequestMetrics Unlimited
bufferPool *bytes.Buffer 64KB (not returned if exceeded)
urlValuesPool url.Values 128 entries
paramsPool *Params 32 entries
streamInfoPool *StreamInfo Unlimited
quicConnPool *QuicConnection Unlimited

HypGo

繁體中文 | English


中文文件

設計文件

套件

AI 協作工具鏈

CLI 命令


English Docs

Design Docs

Packages

AI Collaboration Toolchain

CLI Commands

Clone this wiki locally