Help us shape the future of Go! Take the 2026 Go Developer Survey

handler

package
v0.31.4 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 23, 2026 License: Apache-2.0 Imports: 36 Imported by: 0

README

transport/http/handler/ - HTTP 请求处理器

此目录存放复杂业务场景的 HTTP 请求处理器实现。

与 gen/http/handler 的区别

目录 用途 修改
gen/http/handler/ Hz 生成的骨架代码 可编辑调用逻辑
transport/http/handler/ 复杂 handler 实现 完全手写

使用场景

  • 需要复杂参数处理的接口
  • 需要聚合多个服务的接口
  • 自定义响应格式的接口
  • WebSocket 等特殊协议处理

示例

package handler

import (
    "context"
    
    "github.com/cloudwego/hertz/pkg/app"
    "github.com/pigeonbox/core/app/user"
    "github.com/pigeonbox/core/pkg/resp"
)

type UserHandler struct {
    userSvc *user.Service
}

func NewUserHandler() *UserHandler {
    return &UserHandler{
        userSvc: user.NewService(),
    }
}

func (h *UserHandler) GetUserProfile(ctx context.Context, c *app.RequestContext) {
    userID := c.Param("id")
    
    // 聚合多个服务数据
    userInfo, _ := h.userSvc.GetByID(ctx, userID)
    // orderInfo, _ := h.orderSvc.GetByUserID(ctx, userID)
    
    resp.Success(c, map[string]interface{}{
        "user": userInfo,
        // "orders": orderInfo,
    })
}

注册路由

在 gen/http/router/ 中注册自定义 handler:

// 在路由中间件或自定义路由文件中
userHandler := handler.NewUserHandler()
r.GET("/api/v1/user/:id/profile", userHandler.GetUserProfile)

依赖规则

  • 可以依赖:app/、pkg/
  • 不应直接依赖:repo/(通过 app 层访问)

Documentation

Overview

Package handler 提供定制 HTTP handlers(不走 thrift IDL 生成)。

admin_manage.go 瘦身(2026-10-10):管理端增强 handler(用户 CRUD / 文件管理 / 富统计 / 传输日志 / 分享治理)已全部 IDL 化迁入 gen/handler/admin(契约在 contracts/idl/admin.thrift,路由由 gen/router/admin 注册)。本文件只保留全站 存储实例注入——share 多文件(share_multi.go)与寄件码(file_request.go)的 上传落盘仍依赖 manageStorage,其依赖面维持不动。

P2P 联邦解析代理(GET /api/v1/federation/resolve,手写路由)。 前端在录码本站未命中时经此查询联邦,命中则直跳源节点取件页预填口令; 本端点只做"发现",不代理文件流量(下载始终直连源节点、源节点本地校验)。 未启用联邦时统一 available:false,不区分"未启用/不存在"(降探测面); registry 侧对 resolve 限流最严,本端点不再叠加限流(M4 视压测调参)。

寄件码/反向收件 HTTP 端点(P2)。 2026-10-09 IDL 化(idl/request.thrift):链接管理四端点迁至 core/gen/handler/request/request_service.go(gen/router/request 注册, /api/v1/user 组挂 JWT-only UserAuth);本文件保留访客投递重管道 (multipart 解析/匿名日配额/存储/传输日志/失败清理——包内私有助手依赖), 由 gen/handler/request.GuestUpload 桥接调用。

helpers.go handler 包内样板收口:登录守卫 / 密码守卫 / 路径 ID 解析 / multipart 上传落盘循环。此前同一模式散落 share_multi / localimport / localfiles / file_request / share_user / notify_user / admin_manage 各写一份, 策略调整需逐处同步——统一到本文件单一实现(响应文案/状态码与原各处一致)。

管理端本地文件管理端点(对标上游 2.7.0 data/local 管理;AdminMiddleware 组内)。 路径以「root 索引 + 相对路径」表达,服务端配置为唯一真相源,杜绝穿越。

NAS 本地文件免上传导入端点(P3,手写路由)。

我的通知 mine 三件套已于 2026-10-09 IDL 化(idl/notify.thrift Mine/UnreadCount/MarkRead),handler 迁至 core/gen/handler/notify/notify_service.go, 路由由 gen/router/notify 注册并挂 UserOrAPIKey(_apiMw 手工区)。 本文件仅保留 notify service 注入(notify_public 等消费方)。

OIDC SSO HTTP 端点(P2,手写路由)。

运行时 OpenAPI 规范生成。

背景:openapi.json 曾依赖手工维护的快照文件(拆分后与路由漂移、容器内恒 404, 前端 /api-docs Swagger 页拉不到 spec)。这里改为在路由注册完成后从 hertz 运行时路由表生成「契约级骨架规范」——与实际注册路由零漂移,覆盖端点/方法/ 认证方式/路径参数。

边界(有意为之):骨架不内联请求/响应 schema,字段级真相源在 contracts 仓 thrift IDL;本规范用于端点发现、认证方式说明与 Swagger UI 可用性。

管理端设置测试端点:SMTP 测试发信 / OIDC discovery 验证(AdminMiddleware 组内)。 读取的是叠加后的全局 conf(管理端保存的在线设置已热应用),测的就是"当前生效值"。

取件元数据端点(GET /share/metadata/:code,手写路由)。 查询不扣次数、不要求密码;限流走 download 桶(2026-10-08 起未归桶路径另有全局默认桶兜底), 存在性探测面由 6 位随机码空间 + 统一 404 语义约束。

多文件分享创建端点(P0 多文件,手写路由不走 IDL):

POST /api/v1/share/multi-direct  multipart 多文件直传(小文件)
POST /api/v1/share/multi-bind    绑定已上传的 chunk 会话/presign 对象为一个多文件分享

Package handler 提供定制 HTTP handlers(不走 thrift IDL 生成)。

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AdminDeleteLocalFile

func AdminDeleteLocalFile(ctx context.Context, c *app.RequestContext)

AdminDeleteLocalFile DELETE /admin/local-files?root=0&path=a/b.txt

func AdminImportLocalFile

func AdminImportLocalFile(ctx context.Context, c *app.RequestContext)

AdminImportLocalFile POST /admin/local-files/import 请求体:{root, path, expire_value, expire_style, require_auth, password, custom_code} 管理员把白名单目录内的文件直接生成提取码(服务端拷贝入存储,配额/审核同链路)。

func AdminListLocalFiles

func AdminListLocalFiles(ctx context.Context, c *app.RequestContext)

AdminListLocalFiles GET /admin/local-files?root=0&dir=sub/dir 返回 {roots: [...], entries: [...]}(roots 供前端切换根目录)

func AdminTestOIDC

func AdminTestOIDC(ctx context.Context, c *app.RequestContext)

AdminTestOIDC POST /admin/oidc/test 验证当前生效 OIDC 段的 issuer discovery 端点可达且合法。

func AdminTestSMTP

func AdminTestSMTP(ctx context.Context, c *app.RequestContext)

AdminTestSMTP POST /admin/notify/smtp/test {"to":"you@example.com"} 用当前生效的 notify.smtp 配置向指定邮箱发送测试邮件。

func BuildOpenAPISpec

func BuildOpenAPISpec(routes []OpenAPIRoute, info SpecInfo) []byte

BuildOpenAPISpec 从路由表生成 OpenAPI 3.0 骨架规范

func FederationResolve

func FederationResolve(ctx context.Context, c *app.RequestContext)

FederationResolve 口令联邦解析。

func GuestSubmitFiles

func GuestSubmitFiles(ctx context.Context, c *app.RequestContext)

GuestSubmitFiles 访客投递(POST /api/v1/request/:token/upload,multipart files[])。 显式受邀上传:不走 upload.open_upload 总闸(与 Gokapi File Requests 同策略)。

func ListPublicNotifies added in v0.14.5

func ListPublicNotifies(ctx context.Context, c *app.RequestContext)

ListPublicNotifies 站级公告(匿名公开端点,对标上游首页通知条)。 notify.Active 已限定 target_user_id 为空的全站公告;匿名可访问, 前端 SiteNotice 组件消费(可关闭,localStorage 记忆已读)。

func ManageStorage added in v0.15.2

func ManageStorage() storage.StorageInterface

ManageStorage 取全站存储实例(供需要显式句柄的调用方;缺失返回 nil)。

func MergeWithIDLSpec

func MergeWithIDLSpec(skeleton, idl []byte) []byte

MergeWithIDLSpec 骨架规范 × contracts IDL 规范(openapi.Spec)合并。

设计(2026-10-06 IDL/hz 治理链路):

  • IDL 治理域:paths 下的 operation 以 IDL 条目为准(带完整 request/response schema),但保留骨架独有的 security/tags 字段(认证矩阵真相源在运行时);
  • customizedRegister 手写路由:骨架独有路径/方法原样保留(骨架级、无 schema);
  • components:骨架的 securitySchemes 与 IDL 的 schemas 深并,键冲突 IDL 优先。

任一侧解析失败均回退骨架(可用性优先)。

func MultiShareBind

func MultiShareBind(ctx context.Context, c *app.RequestContext)

MultiShareBind 把多个已上传的 chunk 会话(或 presign 对象 key)绑定为 一个多文件分享。请求体:

{
  "entries": [{"upload_id": "..."} | {"object_key": "...", "file_name": "..."}],
  "expire_value": 1, "expire_style": "day", "require_auth": false, "password": ""
}

@router /api/v1/share/multi-bind [POST]

func MultiShareDirect

func MultiShareDirect(ctx context.Context, c *app.RequestContext)

MultiShareDirect 多文件直传建分享。 @router /api/v1/share/multi-direct [POST]

func OIDCCallback

func OIDCCallback(ctx context.Context, c *app.RequestContext)

OIDCCallback IdP 回调:换发本站 JWT 并 302 回前端(GET /api/v1/user/oidc/callback)

func OIDCLogin

func OIDCLogin(ctx context.Context, c *app.RequestContext)

OIDCLogin 302 跳转到 IdP 授权页(GET /api/v1/user/oidc/login)

func OpenAPISpec

func OpenAPISpec(_ context.Context, c *app.RequestContext)

OpenAPISpec 返回 OpenAPI 3.0 规范 GET /openapi.json 主路径:bootstrap 在路由注册完成后由运行时路由表生成(openapi_gen.go), 与实际注册路由零漂移。文件探测仅作兜底(./static/openapi.json = server 镜像布局;保留以兼容外置 spec 的部署方式)。

func SetFederationService

func SetFederationService(s *federation.Node)

SetFederationService 注入联邦服务(bootstrap 调用;nil = 未启用)

func SetManageStorage added in v0.15.2

func SetManageStorage(st storage.StorageInterface)

SetManageStorage 注入全站存储实例(bootstrap 调用)。

func SetMultiChunkService added in v0.16.0

func SetMultiChunkService(s *chunk.Service)

SetMultiChunkService 注入多文件绑定用 chunk 会话查询服务(bootstrap 调用)。

func SetNotifyService

func SetNotifyService(s *notifyapp.Service)

SetNotifyService 注入 notify service

func SetOIDCService

func SetOIDCService(s *oidcApp.Service)

SetOIDCService 注入 OIDC 服务(bootstrap 调用)

func SetOpenAPISpecBytes

func SetOpenAPISpecBytes(b []byte)

SetOpenAPISpecBytes 注入生成的规范

func SetRequestService

func SetRequestService(s *requestApp.Service)

SetRequestService 注入寄件码服务(bootstrap 调用)

func SetShareService

func SetShareService(s *share.Service)

SetShareService 注入 share service(bootstrap 调用)

func ShareMetadata

func ShareMetadata(ctx context.Context, c *app.RequestContext)

ShareMetadata 元数据查询:供取件页渲染文件名/大小/有效期/剩余次数

func TestOIDCDiscovery added in v0.16.0

func TestOIDCDiscovery(ctx context.Context) error

TestOIDCDiscovery 验证当前生效 OIDC 段的 issuer discovery 端点可达且合法。

func TestSMTPNow added in v0.16.0

func TestSMTPNow(to string) error

TestSMTPNow 用当前生效的 notify.smtp 配置向指定邮箱发送测试邮件。 导出桥(gen handler 委托用;conf 直读面留在本白名单层)。

func UserImportLocal

func UserImportLocal(ctx context.Context, c *app.RequestContext)

UserImportLocal 本地文件导入为分享(POST /api/v1/user/shares/import-local)。 请求体:{path, expire_value, expire_style, require_auth, password, custom_code} 仅登录用户可用;路径必须落在 upload.local_import.roots 白名单内。

Types

type OpenAPIRoute

type OpenAPIRoute struct {
	Method string
	Path   string
}

OpenAPIRoute 参与生成的最小路由信息(与 hertz 路由表类型解耦)

type SpecInfo

type SpecInfo struct {
	Version string // API 版本号(bootstrap 注入)
	BaseURL string // 空则省略 servers
}

SpecInfo 规范元信息

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL