control.go 1.2 KB

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