Files
go-common/examples/middleware_example.go
2025-11-30 13:43:43 +08:00

65 lines
1.5 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package main
import (
"log"
"net/http"
"git.toowon.com/jimmy/go-common/datetime"
"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 := chain.ThenFunc(apiHandler)
// 注册路由
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请求
func apiHandler(w http.ResponseWriter, r *http.Request) {
// 从context获取时区
timezone := http.GetTimezone(r)
// 使用时区进行时间处理
now := datetime.Now(timezone)
startOfDay := datetime.StartOfDay(now, timezone)
endOfDay := datetime.EndOfDay(now, timezone)
// 返回响应
http.Success(w, map[string]interface{}{
"message": "Hello from API",
"timezone": timezone,
"currentTime": datetime.FormatDateTime(now),
"startOfDay": datetime.FormatDateTime(startOfDay),
"endOfDay": datetime.FormatDateTime(endOfDay),
})
}