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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. package tr
  2. import (
  3. "runtime"
  4. "github.com/sirupsen/logrus"
  5. "github.com/wpajqz/linker"
  6. )
  7. type Checker interface {
  8. Check() error
  9. }
  10. func ParseParamFail(ctx linker.Context, param interface{}, fs ...func() error) bool {
  11. if param != nil {
  12. if Fail(ctx, linker.StatusBadRequest, ctx.ParseParam(param)) {
  13. return true
  14. }
  15. if checker, ok := param.(Checker); ok {
  16. return Fail(ctx, linker.StatusBadRequest, checker.Check())
  17. }
  18. }
  19. for _, f := range fs {
  20. if Fail(ctx, linker.StatusBadRequest, f()) {
  21. return true
  22. }
  23. }
  24. return false
  25. }
  26. func Fail(ctx linker.Context, status int, err error) bool {
  27. if err == nil {
  28. return false
  29. }
  30. ctx.Error(status, err.Error())
  31. if status == linker.StatusInternalServerError {
  32. _, file, line, _ := runtime.Caller(1)
  33. logrus.WithField("err", err).Errorf("file:%s line:%d", file, line)
  34. }
  35. return true
  36. }
  37. func Success(ctx linker.Context, data interface{}) {
  38. ctx.Success(data)
  39. }