ngamux:高性能 Go HTTP 路由 - Openclaw Skills
作者:互联网
2026-04-05
什么是 ngamux?
ngamux 是一个为 Go 编程语言编写的流线型 HTTP 路由库,简化了定义端点和管理请求生命周期的过程。通过提供流畅的 API 和强大的基于树的匹配系统,它使开发者能够在使用 Openclaw Skills 时以极低的开销创建可扩展的微服务和 Web 应用程序。该技能专注于开发效率,为处理 JSON 序列化、请求解析和模板渲染等常见任务提供了直观的方法,无需编写标准库中通常涉及的样板代码。
下载入口:https://github.com/openclaw/skills/tree/main/skills/hadihammurabi/ngamux
安装与下载
1. ClawHub CLI
从源直接安装技能的最快方式。
npx clawhub@latest install ngamux
2. 手动安装
将技能文件夹复制到以下位置之一
全局模式~/.openclaw/skills/
工作区
/skills/
优先级:工作区 > 本地 > 内置
3. 提示词安装
将此提示词复制到 OpenClaw 即可自动安装。
请帮我使用 Clawhub 安装 ngamux。如果尚未安装 Clawhub,请先安装(npm i -g clawhub)。
ngamux 应用场景
- 为 RESTful API 定义具有动态路径参数和通配符的复杂 HTTP 端点。
- 为日志记录、身份验证和 CORS 处理实现全局或特定组的中间件。
- 直接将请求体、查询字符串和多部分表单上传中的结构化数据解析到 Go 结构体中。
- 编排分层路由组,以在大规模应用中保持代码库的整洁和模块化。
- 通过高效的路由匹配和自定义序列化策略优化 Web 服务性能。
- 使用可选配置参数(如日志级别和尾随斜杠行为)初始化路由器。
- 使用特定的 HTTP 方法(GET、POST 等)或通配符处理器注册路由,支持动态路径段。
- 在全局或组级别建立中间件链,以便在到达最终处理器之前处理请求。
- 当请求到达时,基于树的匹配器根据路径和方法使用优化的键值存储来识别正确的处理器。
- 请求包装器提供了对参数和负载的便捷访问,而响应助手通过流畅的 API 方便地将格式化数据发送回客户端。
ngamux 配置指南
要在 Openclaw Skills 环境中开始使用,请确保已安装 Go。初始化您的项目并使用以下命令安装软件包:
go get github.com/ngamux/ngamux
基本实现示例:
package main
import (
"github.com/ngamux/ngamux"
"net/http"
)
func main() {
mux := ngamux.New()
mux.Get("/", func(rw http.ResponseWriter, r *http.Request) {
ngamux.Res(rw).Text("Hello via Openclaw Skills")
})
http.ListenAndServe(":8080", mux)
}
ngamux 数据架构与分类体系
ngamux 通过内部请求和响应包装器管理数据,从而实现对 HTTP 元数据的结构化访问。Openclaw Skills 用户可以利用以下数据组织:
| 组件 | 描述 | 数据类型 |
|---|---|---|
| Params | 动态路径段(例如 :id 或 *) | Map[string]string |
| Query | URL 查询字符串参数 | Map[string][]string |
| Locals | 中间件的请求范围上下文存储 | Interface{} |
| Config | 全局路由器设置和 JSON 编组器 | Struct |
| Form | 解析后的多部分和 URL 编码数据 | Struct |
name: ngamux
description: Build and modify web services using ngamux, a simple HTTP router for Go. Define routes, apply middleware, handle requests, and send responses efficiently.
When to use this skill
Use this skill when the user needs to:
- Define HTTP endpoints: Create new routes for various HTTP methods (e.g.,
mux.Get("/users/:id", getUserHandler)) including dynamic path segments (/users/{id}) and wildcards (/files/*filePath). - Implement request preprocessing/postprocessing: Add global middlewares (e.g., for authentication, logging, CORS) or group-specific middlewares to handle requests before they reach the main handler or after they are processed. For example,
mux.Use(authMiddleware)orapiGroup.Use(loggingMiddleware). - Extract incoming data from requests:
- URL Parameters: Retrieve values from dynamic path segments (e.g.,
req.Params("id")). - Query Parameters: Access query string values (e.g.,
req.Query("name", "Guest")). - Form Data: Parse
application/x-www-form-urlencodedormultipart/form-data(e.g.,req.FormValue("username"),req.FormFile("image")). - JSON Payloads: Decode
application/jsonrequest bodies into Go structs (e.g.,req.JSON(&user)).
- URL Parameters: Retrieve values from dynamic path segments (e.g.,
- Construct and send various response types:
- JSON Responses: Send structured data as JSON (e.g.,
ngamux.Res(rw).Status(http.StatusOK).Json(data)). - Text Responses: Send plain text (e.g.,
ngamux.Res(rw).Status(http.StatusOK).Text("Hello, World!")). - HTML Responses: Render HTML templates (e.g.,
ngamux.Res(rw).Status(http.StatusOK).HTML("template.html", data)). - Custom Status Codes: Set specific HTTP status codes for responses.
- JSON Responses: Send structured data as JSON (e.g.,
- Configure router behavior: Adjust global settings like automatically removing trailing slashes (
ngamux.WithTrailingSlash()), setting the logging verbosity (ngamux.WithLogLevel(slog.LevelDebug)), or providing customjson.Marshal/json.Unmarshalfunctions for specific serialization needs. - Organize routes with grouping: Create nested route groups to apply common path prefixes and middlewares to a set of routes (e.g.,
/api/v1). - Debug routing or handler issues: Inspect route definitions, middleware chains, request context, and logging output to diagnose and resolve problems.
Key Functionality
- Route Definition:
ngamuxprovides methods likemux.Get(),mux.Post(),mux.Put(),mux.Delete(),mux.Patch(),mux.Head(), andmux.All()to registerhttp.HandlerFuncs for specific HTTP methods and paths. It supports path parameters (e.g.,/{id}) and wildcards (/*filePath). Routes are efficiently stored and matched using a tree-like structure, leveraging themappingpackage for optimized key-value storage. - Middleware Application: The
mux.Use()method allows global middleware registration, whilemux.Group()andmux.With()enable group-specific middlewares. Middlewares areMiddlewareFunctypes that wraphttp.HandlerFuncs, allowing for a chain of responsibility pattern. TheWithMiddlewaresutility fromcommon.gohandles the functional chaining. - Request Handling: The
Requeststruct (wrapped*http.Request) offers convenience methods:Req().Params(key string): Retrieves URL path parameters parsed during routing.Req().Query(key string, fallback ...string): Accesses URL query string parameters.Req().QueriesParser(data any): Automatically binds query parameters to a Go struct usingquerytags and reflection.Req().FormValue(key string): Gets form field values.Req().FormFile(key string, maxFileSize ...int64): Handles file uploads from multipart forms.Req().JSON(store any): Decodes JSON request bodies into a provided Go interface.Req().Locals(key any, value ...any): Manages request-scoped data in the context.
- Response Handling: The
Responsestruct (wrappedhttp.ResponseWriter) provides a fluent API for crafting responses:Res(rw).Status(code int): Sets the HTTP status code.Res(rw).Text(data string): Sendstext/plaincontent.Res(rw).JSON(data any): Sendsapplication/jsoncontent, using the configured JSON marshaller.Res(rw).HTML(path string, data any): Renders HTML templates usinghtml/template.
- Configuration: Global
Configoptions are set viangamux.New()and functional options likengamux.WithTrailingSlash()andngamux.WithLogLevel(). Custom JSON marshalling/unmarshalling can be provided. - Route Grouping: The
mux.Group(path string)andmux.GroupFunc(path string, router func(mux *Ngamux))methods allow hierarchical organization of routes, where child groups inherit path prefixes and can apply their own set of middlewares, leading to cleaner code organization and shared logic.
相关推荐
专题
+ 收藏
+ 收藏
+ 收藏
+ 收藏
+ 收藏
+ 收藏
最新数据
相关文章
求职信生成器:自动定制职位申请 - Openclaw Skills
核心指标修复工具:通过 Openclaw Skills 优化性能
注释生成器:AI 驱动的代码文档工具 - Openclaw Skills
融资路演内容生成器:AI 初创企业路演内容创作工具 - Openclaw Skills
许可证生成器:自动化开源许可 - Openclaw Skills
落地页生成器:从 package.json 创建 HTML 页面 - Openclaw Skills
jsdoc-gen:自动生成 JSDoc 和 TSDoc 注释 - Openclaw Skills
图像优化器:AI 驱动的性能审计 - Openclaw Skills
Humanize CLI:AI 文本检测与重写 - Openclaw Skills
ESLint 配置生成器:自动代码风格分析 - Openclaw Skills
AI精选
