refl: add hono Context

This commit is contained in:
yangshangbo
2025-07-07 11:27:17 +08:00
parent fc3b70349d
commit a5bf8ebc7c
8 changed files with 948 additions and 609 deletions
+77 -16
View File
@@ -2,31 +2,92 @@ module hono
import net.http
pub struct Request {
// Context 结构体,类似 Hono.js 的实现
pub struct Context {
pub:
url string
param map[string]string
query map[string]string
body string
req http.Request
params map[string]string
query map[string]string
url string
pub mut:
status_code int = 200
headers map[string]string
body string
}
// 接口定义,允许异构的泛型处理器
pub interface IRequestHandler {
// Context 构造函数
pub fn Context.new(req http.Request, params map[string]string, query map[string]string, body string) Context {
return Context{
req: req
params: params
query: query
body: body
url: req.url
headers: map[string]string{}
}
}
// Context 的便捷方法 - 直接返回 http.Response
pub fn (mut c Context) json(data string) http.Response {
mut headers := http.new_header()
headers.add_custom('Content-Type', 'application/json; charset=utf-8') or { }
for key, value in c.headers {
headers.add_custom(key, value) or { continue }
}
return http.Response{
status_code: c.status_code
header: headers
body: data
}
}
pub fn (mut c Context) text(data string) http.Response {
mut headers := http.new_header()
headers.add_custom('Content-Type', 'text/plain; charset=utf-8') or { }
for key, value in c.headers {
headers.add_custom(key, value) or { continue }
}
return http.Response{
status_code: c.status_code
header: headers
body: data
}
}
pub fn (mut c Context) html(data string) http.Response {
mut headers := http.new_header()
headers.add_custom('Content-Type', 'text/html; charset=utf-8') or { }
for key, value in c.headers {
headers.add_custom(key, value) or { continue }
}
return http.Response{
status_code: c.status_code
header: headers
body: data
}
}
pub fn (mut c Context) status(code int) {
c.status_code = code
}
// 处理器接口,使用 Context
pub interface IHandler {
path string
handle(req Request) http.Response
handle(mut c Context) http.Response
}
// 泛型处理器类型
pub type Handler = fn (Request) http.Response
// 泛型处理器类型,使用 Context
pub type ContextHandlerFn = fn (mut Context) http.Response
// 泛型请求处理器结构体
pub struct RequestHandler {
// Context 处理器结构体
pub struct ContextHandler {
pub:
path string
handler fn (Request) http.Response = unsafe { nil }
handler fn (mut Context) http.Response = unsafe { nil }
}
// 实现 IRequestHandler 接口
pub fn (rh RequestHandler) handle(req Request) http.Response {
return rh.handler(req)
// 实现 IHandler 接口
pub fn (ch ContextHandler) handle(mut c Context) http.Response {
return ch.handler(mut c)
}