control.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. package nginx
  2. import (
  3. "net/http"
  4. "strings"
  5. "github.com/gin-gonic/gin"
  6. "github.com/uozi-tech/cosy"
  7. )
  8. type ControlFunc func() (stdOut string, stdErr error)
  9. type ControlResult struct {
  10. stdOut string
  11. stdErr error
  12. }
  13. type ControlResp struct {
  14. Message string `json:"message"`
  15. Level int `json:"level"`
  16. }
  17. func Control(controlFunc ControlFunc) *ControlResult {
  18. stdout, stderr := controlFunc()
  19. return &ControlResult{
  20. stdOut: stdout,
  21. stdErr: stderr,
  22. }
  23. }
  24. func (t *ControlResult) IsError() bool {
  25. return GetLogLevel(t.stdOut) > Warn || t.stdErr != nil
  26. }
  27. func (t *ControlResult) Resp(c *gin.Context) {
  28. if t.IsError() {
  29. t.RespError(c)
  30. return
  31. }
  32. c.JSON(http.StatusOK, ControlResp{
  33. Message: t.stdOut,
  34. Level: GetLogLevel(t.stdOut),
  35. })
  36. }
  37. func (t *ControlResult) RespError(c *gin.Context) {
  38. msg := t.GetOutput()
  39. cosy.ErrHandler(c,
  40. cosy.WrapErrorWithParams(ErrNginx, msg))
  41. }
  42. func (t *ControlResult) GetOutput() string {
  43. if t.stdErr == nil {
  44. return t.stdOut
  45. }
  46. return strings.Join([]string{t.stdOut, t.stdErr.Error()}, " ")
  47. }
  48. func (t *ControlResult) GetError() error {
  49. return cosy.WrapErrorWithParams(ErrNginx, t.GetOutput())
  50. }
  51. func (t *ControlResult) GetLevel() int {
  52. return GetLogLevel(t.stdOut)
  53. }