| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768 |
- package handlers
-
- import (
- "encoding/json"
- "net/http"
- "time"
-
- "git.x2erp.com/qdy/go-base/logger"
- "git.x2erp.com/qdy/go-db/factory/database"
- )
-
- type BaseHandlers struct {
- ServiceName string
- ServiceVersion string
- }
-
- func NewBaseHandlers(name, version string) *BaseHandlers {
- return &BaseHandlers{
- ServiceName: name,
- ServiceVersion: version,
- }
- }
-
- // RootHandler 根处理器
- func (h *BaseHandlers) RootHandler() http.HandlerFunc {
- return func(w http.ResponseWriter, r *http.Request) {
- logger.Debug("接收到根路径请求")
- w.Header().Set("Content-Type", "application/json")
- w.WriteHeader(http.StatusOK)
- w.Write([]byte(`{"service": "` + h.ServiceName + `", "version": "` + h.ServiceVersion + `", "status": "running"}`))
- }
- }
-
- // HealthHandler 健康检查处理器
- func (h *BaseHandlers) HealthHandler(dbFactory *database.DBFactory) http.HandlerFunc {
- return func(w http.ResponseWriter, r *http.Request) {
- logger.Debug("接收到健康检查请求")
- w.Header().Set("Content-Type", "application/json")
-
- if dbFactory == nil {
- w.WriteHeader(http.StatusServiceUnavailable)
- w.Write([]byte(`{"status": "unhealthy", "error": "database not initialized"}`))
- return
- }
-
- w.WriteHeader(http.StatusOK)
- w.Write([]byte(`{"status": "healthy", "service": "` + h.ServiceName + `"}`))
- }
- }
-
- // InfoHandler 信息处理器
- func (h *BaseHandlers) InfoHandler() http.HandlerFunc {
- return func(w http.ResponseWriter, r *http.Request) {
- logger.Debug("接收到信息查询请求")
- w.Header().Set("Content-Type", "application/json")
-
- info := map[string]interface{}{
- "service": h.ServiceName,
- "version": h.ServiceVersion,
- "status": "running",
- "timestamp": time.Now().Format(time.RFC3339),
- }
-
- jsonData, _ := json.Marshal(info)
- w.WriteHeader(http.StatusOK)
- w.Write(jsonData)
- }
- }
|