-
Notifications
You must be signed in to change notification settings - Fork 0
context_en.md
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.
-
Standard Library Compatible: Provides methods to wrap HypGo's
*Contextintocontext.Contextor extract it. Ideal for calling third-party libraries that require the standardcontext.Contextoutside the framework. -
Unified Response Interface: Provides convenient methods such as
JSON(),XML(),String(),HTML(), andFile()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'sAcceptheader. -
Object Pooling:
Context,ResponseWriter,RequestMetrics,Params,Buffer,URLValuesall usesync.Poolmanagement, 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.
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", }) }
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() }
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") }
The Context package employs multiple GC optimizations targeting high QPS scenarios (>100k req/s) to reduce pause times:
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.
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.
| 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 |
設計文件
套件
- config — 設定
- context — 請求上下文
- router — 路由器
- server — 伺服器
- middleware — 中介層
- websocket — WebSocket
- hidb — 資料庫 ORM
- hidb/cassandra — Cassandra
- logger — 日誌
- json — JSON 處理
- grpc — gRPC
AI 協作工具鏈
- schema — Schema-first 路由
- manifest — 專案 Manifest
- contract — Contract Testing
- errors — Typed Error Catalog
- migrate — Migration Diff
- scaffold — 智慧 Scaffold
- airules — AI Rules
CLI 命令
- hyp 總覽
- hyp new
- hyp api
- hyp run
- hyp restart
- hyp generate
- hyp migrate
- hyp context
- hyp ai-rules
- hyp chkcomment
- hyp impact
- hyp docker
- hyp health
- hyp version
- hyp difflog
Design Docs
Packages
- config — Configuration
- context — Request Context
- router — Router
- server — Server
- middleware — Middleware
- websocket — WebSocket
- hidb — Database ORM
- hidb/cassandra - Cassandra 5.0
- logger — Logger
- json — JSON
- grpc — gRPC
AI Collaboration Toolchain
- schema — Schema-first Routing
- manifest — Project Manifest
- contract — Contract Testing
- errors — Typed Error Catalog
- migrate — Migration Diff
- scaffold — Smart Scaffold
- airules — AI Rules
CLI Commands