重构项目的实现,优化使用方法与使用逻辑

This commit is contained in:
2026-06-25 00:03:59 +08:00
parent a6e8101e09
commit 6072ec57e8
49 changed files with 1663 additions and 12534 deletions

View File

@@ -1,40 +1,30 @@
//go:build example
// +build example
package main
import (
"log"
"net/http"
"git.toowon.com/jimmy/go-common/factory"
commonhttp "git.toowon.com/jimmy/go-common/http"
"git.toowon.com/jimmy/go-common/middleware"
)
// 示例:简单的中间件配置
// 包括Recovery、Logging、CORS、Timezone
func main() {
// 创建简单的中间件链(使用默认配置)
chain := middleware.NewChain(
middleware.Recovery(nil), // Panic恢复使用默认logger
middleware.Logging(nil), // 请求日志使用默认logger
middleware.CORS(nil), // CORS允许所有源
middleware.Timezone, // 时区处理默认AsiaShanghai
)
if err := factory.Init("config.json"); err != nil {
log.Fatal(err)
}
app := factory.Default()
chain := app.MiddlewareChain()
// 定义API处理器
http.Handle("/api/hello", chain.ThenFunc(func(w http.ResponseWriter, r *http.Request) {
// 获取时区(使用公共方法)
timezone := commonhttp.GetTimezone(r)
// 返回响应(使用公共方法)
commonhttp.Success(w, map[string]interface{}{
h := commonhttp.NewHandler(w, r)
h.Success(map[string]any{
"message": "Hello, World!",
"timezone": timezone,
"timezone": h.GetTimezone(),
})
}))
// 启动服务器
addr := ":8080"
log.Printf("Server starting on %s", addr)
log.Printf("Try: http://localhost%s/api/hello", addr)
log.Fatal(http.ListenAndServe(addr, nil))
log.Fatal(http.ListenAndServe(":8080", nil))
}