另客网go项目公用的代码库

tr.go 1.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. package tr
  2. import (
  3. "github.com/wpajqz/linker"
  4. )
  5. type Checker interface {
  6. Check() error
  7. }
  8. func ParseParamFail(ctx linker.Context, param interface{}, fs ...func() error) bool {
  9. if param != nil {
  10. err := ctx.ParseParam(param)
  11. if err != nil {
  12. err = TCPError{Status: linker.StatusBadRequest, Msg: err.Error()}
  13. return Fail(ctx, err)
  14. }
  15. if checker, ok := param.(Checker); ok {
  16. err := checker.Check()
  17. if err != nil {
  18. err = TCPError{Status: linker.StatusBadRequest, Msg: err.Error()}
  19. return Fail(ctx, checker.Check())
  20. }
  21. }
  22. }
  23. for _, f := range fs {
  24. err := f()
  25. if err != nil {
  26. err = TCPError{Status: linker.StatusBadRequest, Msg: err.Error()}
  27. return Fail(ctx, err)
  28. }
  29. }
  30. return false
  31. }
  32. func Fail(ctx linker.Context, err error) bool {
  33. if err == nil {
  34. return false
  35. }
  36. status := linker.StatusInternalServerError
  37. if v, ok := err.(TCPError); ok {
  38. status = v.Status
  39. }
  40. ctx.Error(status, err.Error())
  41. return true
  42. }
  43. func Success(ctx linker.Context, data interface{}) {
  44. ctx.Success(data)
  45. }