65 lines
1.5 KiB
Go
65 lines
1.5 KiB
Go
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),
|
||
})
|
||
}
|
||
|