Util.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. package base
  2. import (
  3. log "Server-Core/Server/Base/Log"
  4. "bytes"
  5. "runtime"
  6. "strconv"
  7. "strings"
  8. "time"
  9. )
  10. // 字符串首字母转大写
  11. func StrFirstToUpper(str string) string {
  12. if len(str) < 1 {
  13. return ""
  14. }
  15. strArray := []rune(str)
  16. if strArray[0] >= 97 && strArray[0] <= 122 {
  17. strArray[0] -= 32
  18. }
  19. return string(strArray)
  20. }
  21. // 两个时间戳是否同一天
  22. func IsSameDay(time1, time2 int64, offset int) bool {
  23. return StartTimestamp(time1, offset) == StartTimestamp(time2, offset)
  24. }
  25. // 获取今天0点时间戳(计算时差)
  26. func TodayStartTimestamp(offset int) int64 {
  27. return StartTimestamp(time.Now().Unix(), offset)
  28. }
  29. // 获取指定时间戳的0点时间戳(计算时差)
  30. func StartTimestamp(timestamp int64, offset int) int64 {
  31. timeStr := time.Unix(timestamp, 0).Format("2006-01-02")
  32. t, _ := time.Parse("2006-01-02", timeStr)
  33. t2 := t.Unix() + int64(offset)
  34. if t2 > timestamp {
  35. t2 -= 86400
  36. }
  37. return t2
  38. }
  39. // unicode转中文
  40. func Unicode2Hans(raw []byte) []byte {
  41. str, err := strconv.Unquote(strings.Replace(strconv.Quote(string(raw)), `\\u`, `\u`, -1))
  42. if err != nil {
  43. return raw
  44. }
  45. return []byte(str)
  46. }
  47. // 打印Panic堆栈信息
  48. func PanicTrace(kb int) string {
  49. s := []byte("/src/runtime/panic.go")
  50. e := []byte("\ngoroutine ")
  51. line := []byte("\n")
  52. stack := make([]byte, kb<<10) //4KB
  53. length := runtime.Stack(stack, true)
  54. start := bytes.Index(stack, s)
  55. stack = stack[start:length]
  56. start = bytes.Index(stack, line) + 1
  57. stack = stack[start:]
  58. end := bytes.LastIndex(stack, line)
  59. if end != -1 {
  60. stack = stack[:end]
  61. }
  62. end = bytes.Index(stack, e)
  63. if end != -1 {
  64. stack = stack[:end]
  65. }
  66. stack = bytes.TrimRight(stack, "\n")
  67. return string(stack)
  68. }
  69. // 通用异常捕获
  70. func TryE() {
  71. errs := recover()
  72. if errs == nil {
  73. return
  74. }
  75. log.Error("%v\n", errs)
  76. log.Error(panicTrace(8))
  77. }
  78. func panicTrace(kb int) string {
  79. s := []byte("/src/runtime/panic.go")
  80. e := []byte("\ngoroutine ")
  81. line := []byte("\n")
  82. stack := make([]byte, kb<<10) //4KB
  83. length := runtime.Stack(stack, true)
  84. start := bytes.Index(stack, s)
  85. stack = stack[start:length]
  86. start = bytes.Index(stack, line) + 1
  87. stack = stack[start:]
  88. end := bytes.LastIndex(stack, line)
  89. if end != -1 {
  90. stack = stack[:end]
  91. }
  92. end = bytes.Index(stack, e)
  93. if end != -1 {
  94. stack = stack[:end]
  95. }
  96. stack = bytes.TrimRight(stack, "\n")
  97. return string(stack)
  98. }