package main import ( "log" "net/http" "git.toowon.com/jimmy/go-common/datetime" commonhttp "git.toowon.com/jimmy/go-common/http" "git.toowon.com/jimmy/go-common/middleware" ) // 示例:使用CORS和时区中间件 func main() { // 配置CORS corsConfig := &middleware.CORSConfig{ AllowedOrigins: []string{"*"}, AllowedMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"}, AllowedHeaders: []string{ "Content-Type", "Authorization", "X-Requested-With", "X-Timezone", }, AllowCredentials: false, MaxAge: 3600, } // 创建中间件链 chain := middleware.NewChain( middleware.CORS(corsConfig), middleware.Timezone, ) // 定义处理器(使用Handler模式) handler := chain.ThenFunc(func(w http.ResponseWriter, r *http.Request) { h := commonhttp.NewHandler(w, r) apiHandler(h) }) // 注册路由 http.Handle("/api", handler) log.Println("Server started on :8080") log.Println("Try: curl -H 'X-Timezone: America/New_York' http://localhost:8080/api") log.Fatal(http.ListenAndServe(":8080", nil)) } // apiHandler 处理API请求(使用Handler模式) func apiHandler(h *commonhttp.Handler) { // 从Handler获取时区 timezone := h.GetTimezone() // 使用时区进行时间处理 now := datetime.Now(timezone) startOfDay := datetime.StartOfDay(now, timezone) endOfDay := datetime.EndOfDay(now, timezone) // 返回响应 h.Success(map[string]interface{}{ "message": "Hello from API", "timezone": timezone, "currentTime": datetime.FormatDateTime(now), "startOfDay": datetime.FormatDateTime(startOfDay), "endOfDay": datetime.FormatDateTime(endOfDay), }) }