utils.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. package pkg
  2. import (
  3. "errors"
  4. "log"
  5. "runtime"
  6. "strconv"
  7. "github.com/gin-gonic/gin"
  8. "github.com/google/uuid"
  9. "golang.org/x/crypto/bcrypt"
  10. "gorm.io/gorm"
  11. )
  12. const (
  13. TrafficKey = "X-Request-Id"
  14. LoggerKey = "_OAuth-logger-request"
  15. )
  16. func CompareHashAndPassword(e string, p string) (bool, error) {
  17. err := bcrypt.CompareHashAndPassword([]byte(e), []byte(p))
  18. if err != nil {
  19. return false, err
  20. }
  21. return true, nil
  22. }
  23. // Assert 条件断言
  24. // 当断言条件为 假 时触发 panic
  25. // 对于当前请求不会再执行接下来的代码,并且返回指定格式的错误信息和错误码
  26. func Assert(condition bool, msg string, code ...int) {
  27. if !condition {
  28. statusCode := 200
  29. if len(code) > 0 {
  30. statusCode = code[0]
  31. }
  32. panic("CustomError#" + strconv.Itoa(statusCode) + "#" + msg)
  33. }
  34. }
  35. // HasError 错误断言
  36. // 当 error 不为 nil 时触发 panic
  37. // 对于当前请求不会再执行接下来的代码,并且返回指定格式的错误信息和错误码
  38. // 若 msg 为空,则默认为 error 中的内容
  39. func HasError(err error, msg string, code ...int) {
  40. if err != nil {
  41. statusCode := 200
  42. if len(code) > 0 {
  43. statusCode = code[0]
  44. }
  45. if msg == "" {
  46. msg = err.Error()
  47. }
  48. _, file, line, _ := runtime.Caller(1)
  49. log.Printf("%s:%v error: %#v", file, line, err)
  50. panic("CustomError#" + strconv.Itoa(statusCode) + "#" + msg)
  51. }
  52. }
  53. // GenerateMsgIDFromContext 生成msgID
  54. func GenerateMsgIDFromContext(c *gin.Context) string {
  55. requestId := c.GetHeader(TrafficKey)
  56. if requestId == "" {
  57. requestId = uuid.New().String()
  58. c.Header(TrafficKey, requestId)
  59. }
  60. return requestId
  61. }
  62. // GetOrm 获取orm连接
  63. func GetOrm(c *gin.Context) (*gorm.DB, error) {
  64. idb, exist := c.Get("db")
  65. if !exist {
  66. return nil, errors.New("db connect not exist")
  67. }
  68. switch idb.(type) {
  69. case *gorm.DB:
  70. //新增操作
  71. return idb.(*gorm.DB), nil
  72. default:
  73. return nil, errors.New("db connect not exist")
  74. }
  75. }