supervisor.go 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. package supervisor
  2. import (
  3. "time"
  4. "go-common/library/ecode"
  5. bm "go-common/library/net/http/blademaster"
  6. )
  7. // Config supervisor conf.
  8. type Config struct {
  9. On bool // all post/put/delete method off.
  10. Begin time.Time // begin time
  11. End time.Time // end time
  12. }
  13. // Supervisor supervisor midleware.
  14. type Supervisor struct {
  15. conf *Config
  16. on bool
  17. }
  18. // New new and return supervisor midleware.
  19. func New(c *Config) (s *Supervisor) {
  20. s = &Supervisor{
  21. conf: c,
  22. }
  23. s.Reload(c)
  24. return
  25. }
  26. // Reload reload supervisor conf.
  27. func (s *Supervisor) Reload(c *Config) {
  28. if c == nil {
  29. return
  30. }
  31. s.on = c.On && c.Begin.Before(c.End)
  32. s.conf = c // NOTE datarace but no side effect.
  33. }
  34. func (s *Supervisor) ServeHTTP(c *bm.Context) {
  35. if s.on {
  36. now := time.Now()
  37. method := c.Request.Method
  38. if s.forbid(method, now) {
  39. c.JSON(nil, ecode.ServiceUpdate)
  40. c.Abort()
  41. return
  42. }
  43. }
  44. }
  45. func (s *Supervisor) forbid(method string, now time.Time) bool {
  46. // only allow GET request.
  47. return method != "GET" && now.Before(s.conf.End) && now.After(s.conf.Begin)
  48. }