Keine Beschreibung
Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. package handlers
  2. import (
  3. "encoding/json"
  4. "net/http"
  5. "time"
  6. "git.x2erp.com/qdy/go-base/logger"
  7. "git.x2erp.com/qdy/go-db/factory/database"
  8. )
  9. type BaseHandlers struct {
  10. ServiceName string
  11. ServiceVersion string
  12. }
  13. func NewBaseHandlers(name, version string) *BaseHandlers {
  14. return &BaseHandlers{
  15. ServiceName: name,
  16. ServiceVersion: version,
  17. }
  18. }
  19. // RootHandler 根处理器
  20. func (h *BaseHandlers) RootHandler() http.HandlerFunc {
  21. return func(w http.ResponseWriter, r *http.Request) {
  22. logger.Debug("接收到根路径请求")
  23. w.Header().Set("Content-Type", "application/json")
  24. w.WriteHeader(http.StatusOK)
  25. w.Write([]byte(`{"service": "` + h.ServiceName + `", "version": "` + h.ServiceVersion + `", "status": "running"}`))
  26. }
  27. }
  28. // HealthHandler 健康检查处理器
  29. func (h *BaseHandlers) HealthHandler(dbFactory *database.DBFactory) http.HandlerFunc {
  30. return func(w http.ResponseWriter, r *http.Request) {
  31. logger.Debug("接收到健康检查请求")
  32. w.Header().Set("Content-Type", "application/json")
  33. if dbFactory == nil {
  34. w.WriteHeader(http.StatusServiceUnavailable)
  35. w.Write([]byte(`{"status": "unhealthy", "error": "database not initialized"}`))
  36. return
  37. }
  38. w.WriteHeader(http.StatusOK)
  39. w.Write([]byte(`{"status": "healthy", "service": "` + h.ServiceName + `"}`))
  40. }
  41. }
  42. // InfoHandler 信息处理器
  43. func (h *BaseHandlers) InfoHandler() http.HandlerFunc {
  44. return func(w http.ResponseWriter, r *http.Request) {
  45. logger.Debug("接收到信息查询请求")
  46. w.Header().Set("Content-Type", "application/json")
  47. info := map[string]interface{}{
  48. "service": h.ServiceName,
  49. "version": h.ServiceVersion,
  50. "status": "running",
  51. "timestamp": time.Now().Format(time.RFC3339),
  52. }
  53. jsonData, _ := json.Marshal(info)
  54. w.WriteHeader(http.StatusOK)
  55. w.Write(jsonData)
  56. }
  57. }