healthcheck.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. // Copyright 2013 Beego Authors
  2. // Copyright 2014 The Macaron Authors
  3. //
  4. // Licensed under the Apache License, Version 2.0 (the "License"): you may
  5. // not use this file except in compliance with the License. You may obtain
  6. // a copy of the License at
  7. //
  8. // http://www.apache.org/licenses/LICENSE-2.0
  9. //
  10. // Unless required by applicable law or agreed to in writing, software
  11. // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  12. // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  13. // License for the specific language governing permissions and limitations
  14. // under the License.
  15. package toolbox
  16. import (
  17. "bytes"
  18. )
  19. // HealthChecker represents a health check instance.
  20. type HealthChecker interface {
  21. Desc() string
  22. Check() error
  23. }
  24. // HealthCheckFunc represents a callable function for health check.
  25. type HealthCheckFunc func() error
  26. // HealthCheckFunc represents a callable function for health check with description.
  27. type HealthCheckFuncDesc struct {
  28. Desc string
  29. Func HealthCheckFunc
  30. }
  31. type healthCheck struct {
  32. desc string
  33. HealthChecker
  34. check HealthCheckFunc // Not nil if add job as a function.
  35. }
  36. // AddHealthCheck adds new health check job.
  37. func (t *toolbox) AddHealthCheck(hc HealthChecker) {
  38. t.healthCheckJobs = append(t.healthCheckJobs, &healthCheck{
  39. HealthChecker: hc,
  40. })
  41. }
  42. // AddHealthCheckFunc adds a function as a new health check job.
  43. func (t *toolbox) AddHealthCheckFunc(desc string, fn HealthCheckFunc) {
  44. t.healthCheckJobs = append(t.healthCheckJobs, &healthCheck{
  45. desc: desc,
  46. check: fn,
  47. })
  48. }
  49. func (t *toolbox) handleHealthCheck() string {
  50. if len(t.healthCheckJobs) == 0 {
  51. return "no health check jobs"
  52. }
  53. var buf bytes.Buffer
  54. var err error
  55. for _, job := range t.healthCheckJobs {
  56. buf.WriteString("* ")
  57. if job.check != nil {
  58. buf.WriteString(job.desc)
  59. err = job.check()
  60. } else {
  61. buf.WriteString(job.Desc())
  62. err = job.Check()
  63. }
  64. buf.WriteString(": ")
  65. if err == nil {
  66. buf.WriteString("OK")
  67. } else {
  68. buf.WriteString(err.Error())
  69. }
  70. buf.WriteString("\n")
  71. }
  72. return buf.String()
  73. }