Files
go-common/examples/middleware_simple_example.go

43 lines
1.1 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"
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
)
// 定义API处理器
http.Handle("/api/hello", chain.ThenFunc(func(w http.ResponseWriter, r *http.Request) {
h := commonhttp.NewHandler(w, r)
// 获取时区
timezone := h.GetTimezone()
// 返回响应
h.Success(map[string]interface{}{
"message": "Hello, World!",
"timezone": timezone,
})
}))
// 启动服务器
addr := ":8080"
log.Printf("Server starting on %s", addr)
log.Printf("Try: http://localhost%s/api/hello", addr)
log.Fatal(http.ListenAndServe(addr, nil))
}