common.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  1. package common
  2. import (
  3. "bytes"
  4. "fmt"
  5. "github.com/gin-gonic/gin"
  6. "net/http"
  7. )
  8. type ResponseJson struct {
  9. Code uint `yaml:"code" json:"code"` // response code
  10. Message string `yaml:"message" json:"message"` // response message
  11. Data interface{} `yaml:"data" json:"data,omitempty"` // response data
  12. }
  13. /**
  14. 生成Response
  15. */
  16. func GenResp(c *gin.Context, code int, message string, data interface{}) {
  17. if data != nil {
  18. c.JSON(http.StatusOK, gin.H{
  19. "code": code,
  20. "message": message,
  21. "data": data,
  22. })
  23. } else {
  24. c.JSON(http.StatusOK, gin.H{
  25. "code": code,
  26. "message": message,
  27. })
  28. }
  29. }
  30. /**
  31. 生成带错误信息的Response
  32. */
  33. func GenMessageResp(c *gin.Context, code int, msg string, data interface{}) {
  34. if data != nil {
  35. c.JSON(http.StatusOK, gin.H{
  36. "code": code,
  37. "message": msg,
  38. "data": data,
  39. })
  40. } else {
  41. c.JSON(http.StatusOK, gin.H{
  42. "code": code,
  43. "message": msg,
  44. })
  45. }
  46. }
  47. // StringsJoin string array join
  48. func StringsJoin(strs ...string) string {
  49. var str string
  50. var b bytes.Buffer
  51. strsLen := len(strs)
  52. if strsLen == 0 {
  53. return str
  54. }
  55. for i := 0; i < strsLen; i++ {
  56. b.WriteString(strs[i])
  57. }
  58. str = b.String()
  59. return str
  60. }
  61. func Join2String(split string, strs ...interface{}) string {
  62. var str string
  63. var b bytes.Buffer
  64. strsLen := len(strs)
  65. if strsLen == 0 {
  66. return str
  67. }
  68. for i := 0; i < strsLen; i++ {
  69. var str interface{}
  70. switch str.(type) {
  71. case string:
  72. b.WriteString(str.(string))
  73. case int:
  74. b.WriteString(fmt.Sprintf("%d", str.(int)))
  75. case int64:
  76. b.WriteString(fmt.Sprintf("%d", str.(int)))
  77. }
  78. }
  79. str = b.String()
  80. return str
  81. }
  82. func LogError(msg string) {
  83. if LoggerInfo.Open {
  84. Logger.Error(msg)
  85. }
  86. }
  87. func LogInfo(msg string) {
  88. if LoggerInfo.Open {
  89. Logger.Info(msg)
  90. }
  91. }
  92. func LogDebug(msg string) {
  93. if LoggerInfo.Open {
  94. Logger.Debug(msg)
  95. }
  96. }
  97. func LogWarn(msg string) {
  98. if LoggerInfo.Open {
  99. Logger.Warn(msg)
  100. }
  101. }
  102. func LogSync() error {
  103. if LoggerInfo.Open {
  104. return Logger.Sync()
  105. }
  106. return nil
  107. }