random-api-go/router/router.go
wood chen e70ca4cf52 feat(docker, config, api): update docker-compose for logging, enhance app structure, and add system metrics display
- Updated docker-compose.yml to mount logs directory.
- Changed BASE_URL environment variable to point to the new API endpoint.
- Refactored main.go to implement a structured App type, improving initialization and graceful shutdown.
- Enhanced config management with JSON loading and environment variable support.
- Added monitoring capabilities in api_handler for logging request metrics.
- Introduced new metrics display in index.html with corresponding CSS styles for better visualization.
2024-11-30 23:23:58 +08:00

41 lines
718 B
Go

package router
import (
"net/http"
"random-api-go/middleware"
)
type Router struct {
mux *http.ServeMux
}
type Handler interface {
Setup(r *Router)
}
func New() *Router {
return &Router{
mux: http.NewServeMux(),
}
}
func (r *Router) Setup(h Handler) {
// 静态文件服务
fileServer := http.FileServer(http.Dir("./public"))
r.mux.Handle("/", middleware.Chain(
middleware.Recovery,
middleware.MetricsMiddleware,
)(fileServer))
// 设置API路由
h.Setup(r)
}
func (r *Router) HandleFunc(pattern string, handler func(http.ResponseWriter, *http.Request)) {
r.mux.HandleFunc(pattern, handler)
}
func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) {
r.mux.ServeHTTP(w, req)
}