初始版本,工具基础类
This commit is contained in:
64
examples/middleware_example.go
Normal file
64
examples/middleware_example.go
Normal file
@@ -0,0 +1,64 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"log"
|
||||
"net/http"
|
||||
|
||||
"github.com/go-common/datetime"
|
||||
"github.com/go-common/http"
|
||||
"github.com/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),
|
||||
})
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user