ngamux
使用 ngamux(一个简单的 Go HTTP 路由器)构建和修改 Web 服务。有效地定义路由、应用中间件、处理请求并发送响应。
安装 / 下载方式
TotalClaw CLI推荐
totalclaw skills install shop:totalclaw:totalclaw~hadihammurabi-ngamuxcURL直接下载,无需登录
curl -fsSL https://skills.taituai.com/api/skills/totalclaw%3Atotalclaw~hadihammurabi-ngamux/file -o hadihammurabi-ngamux.md## 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)` or `apiGroup.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-urlencoded` or `multipart/form-data` (e.g., `req.FormValue("username")`, `req.FormFile("image")`).
- **JSON Payloads**: Decode `application/json` request bodies into Go structs (e.g., `req.JSON(&user)`).
- **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.
- **Configure router behavior**: Adjust global settings like automatically removing trailing slashes (`ngamux.WithTrailingSlash()`), setting the logging verbosity (`ngamux.WithLogLevel(slog.LevelDebug)`), or providing custom `json.Marshal`/`json.Unmarshal` functions 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**: `ngamux` provides methods like `mux.Get()`, `mux.Post()`, `mux.Put()`, `mux.Delete()`, `mux.Patch()`, `mux.Head()`, and `mux.All()` to register `http.HandlerFunc`s 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 the `mapping` package for optimized key-value storage.
- **Middleware Application**: The `mux.Use()` method allows global middleware registration, while `mux.Group()` and `mux.With()` enable group-specific middlewares. Middlewares are `MiddlewareFunc` types that wrap `http.HandlerFunc`s, allowing for a chain of responsibility pattern. The `WithMiddlewares` utility from `common.go` handles the functional chaining.
- **Request Handling**: The `Request` struct (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 using `query` tags 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 `Response` struct (wrapped `http.ResponseWriter`) provides a fluent API for crafting responses:
- `Res(rw).Status(code int)`: Sets the HTTP status code.
- `Res(rw).Text(data string)`: Sends `text/plain` content.
- `Res(rw).JSON(data any)`: Sends `application/json` content, using the configured JSON marshaller.
- `Res(rw).HTML(path string, data any)`: Renders HTML templates using `html/template`.
- **Configuration**: Global `Config` options are set via `ngamux.New()` and functional options like `ngamux.WithTrailingSlash()` and `ngamux.WithLogLevel()`. Custom JSON marshalling/unmarshalling can be provided.
- **Route Grouping**: The `mux.Group(path string)` and `mux.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.
---
## 中文说明
## 何时使用此技能
在用户需要执行以下操作时使用此技能:
- **定义 HTTP 端点**:为各种 HTTP 方法创建新路由(例如 `mux.Get("/users/:id", getUserHandler)`),包括动态路径段(`/users/{id}`)和通配符(`/files/*filePath`)。
- **实现请求的前置/后置处理**:添加全局中间件(例如用于身份验证、日志记录、CORS)或分组专用中间件,以便在请求到达主处理器之前或处理之后进行处理。例如 `mux.Use(authMiddleware)` 或 `apiGroup.Use(loggingMiddleware)`。
- **从请求中提取传入数据**:
- **URL 参数**:从动态路径段中获取值(例如 `req.Params("id")`)。
- **查询参数**:访问查询字符串的值(例如 `req.Query("name", "Guest")`)。
- **表单数据**:解析 `application/x-www-form-urlencoded` 或 `multipart/form-data`(例如 `req.FormValue("username")`、`req.FormFile("image")`)。
- **JSON 负载**:将 `application/json` 请求体解码为 Go 结构体(例如 `req.JSON(&user)`)。
- **构造并发送各种响应类型**:
- **JSON 响应**:以 JSON 形式发送结构化数据(例如 `ngamux.Res(rw).Status(http.StatusOK).Json(data)`)。
- **文本响应**:发送纯文本(例如 `ngamux.Res(rw).Status(http.StatusOK).Text("Hello, World!")`)。
- **HTML 响应**:渲染 HTML 模板(例如 `ngamux.Res(rw).Status(http.StatusOK).HTML("template.html", data)`)。
- **自定义状态码**:为响应设置特定的 HTTP 状态码。
- **配置路由器行为**:调整全局设置,例如自动移除尾部斜杠(`ngamux.WithTrailingSlash()`)、设置日志详细程度(`ngamux.WithLogLevel(slog.LevelDebug)`),或为特定序列化需求提供自定义的 `json.Marshal`/`json.Unmarshal` 函数。
- **用分组组织路由**:创建嵌套路由组,以便为一组路由应用公共路径前缀和中间件(例如 `/api/v1`)。
- **调试路由或处理器问题**:检查路由定义、中间件链、请求上下文和日志输出,以诊断和解决问题。
## 关键功能
- **路由定义**:`ngamux` 提供 `mux.Get()`、`mux.Post()`、`mux.Put()`、`mux.Delete()`、`mux.Patch()`、`mux.Head()` 和 `mux.All()` 等方法,为特定 HTTP 方法和路径注册 `http.HandlerFunc`。它支持路径参数(例如 `/{id}`)和通配符(`/*filePath`)。路由通过树状结构高效存储和匹配,借助 `mapping` 包实现优化的键值存储。
- **中间件应用**:`mux.Use()` 方法允许注册全局中间件,而 `mux.Group()` 和 `mux.With()` 则支持分组专用中间件。中间件是 `MiddlewareFunc` 类型,用于包装 `http.HandlerFunc`,从而实现责任链模式。`common.go` 中的 `WithMiddlewares` 工具负责处理函数式链接。
- **请求处理**:`Request` 结构体(包装 `*http.Request`)提供了便捷方法:
- `Req().Params(key string)`:获取路由期间解析的 URL 路径参数。
- `Req().Query(key string, fallback ...string)`:访问 URL 查询字符串参数。
- `Req().QueriesParser(data any)`:使用 `query` 标签和反射,自动将查询参数绑定到 Go 结构体。
- `Req().FormValue(key string)`:获取表单字段值。
- `Req().FormFile(key string, maxFileSize ...int64)`:处理 multipart 表单的文件上传。
- `Req().JSON(store any)`:将 JSON 请求体解码到提供的 Go 接口中。
- `Req().Locals(key any, value ...any)`:在上下文中管理请求级数据。
- **响应处理**:`Response` 结构体(包装 `http.ResponseWriter`)提供流式 API 来构造响应:
- `Res(rw).Status(code int)`:设置 HTTP 状态码。
- `Res(rw).Text(data string)`:发送 `text/plain` 内容。
- `Res(rw).JSON(data any)`:使用已配置的 JSON 编组器发送 `application/json` 内容。
- `Res(rw).HTML(path string, data any)`:使用 `html/template` 渲染 HTML 模板。
- **配置**:全局 `Config` 选项通过 `ngamux.New()` 以及 `ngamux.WithTrailingSlash()` 和 `ngamux.WithLogLevel()` 等函数式选项进行设置。可提供自定义的 JSON 编组/解组。
- **路由分组**:`mux.Group(path string)` 和 `mux.GroupFunc(path string, router func(mux *Ngamux))` 方法允许对路由进行层级化组织,其中子组继承路径前缀并可应用自己的中间件集合,从而带来更清晰的代码组织和共享逻辑。