tools.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. package utils
  2. import (
  3. "crypto/md5"
  4. "encoding/json"
  5. "fmt"
  6. "reflect"
  7. "runtime/debug"
  8. )
  9. func Md5(str string) string {
  10. t := md5.Sum(([]byte)(str))
  11. return fmt.Sprintf("%x", t)
  12. }
  13. func CopyStructByJson(src, dst interface{}) {
  14. str, _ := json.Marshal(src)
  15. err := json.Unmarshal(str, dst)
  16. if err != nil {
  17. return
  18. }
  19. }
  20. // CopyStructToMap 结构体转map
  21. func CopyStructToMap(src interface{}) map[string]interface{} {
  22. var res = map[string]interface{}{}
  23. str, _ := json.Marshal(src)
  24. err := json.Unmarshal(str, &res)
  25. if err != nil {
  26. return nil
  27. }
  28. return res
  29. }
  30. // SafeGo is a common function to recover panic for goroutines
  31. func SafeGo(f interface{}, params ...interface{}) {
  32. go func() {
  33. defer func() {
  34. if r := recover(); r != nil {
  35. fmt.Printf("Recovered in SafeGo: %v\n", r)
  36. debug.PrintStack()
  37. }
  38. }()
  39. // Convert f to a reflect.Value
  40. funcValue := reflect.ValueOf(f)
  41. // Check if the f is a function
  42. if funcValue.Kind() != reflect.Func {
  43. fmt.Println("SafeGo: value is not a function")
  44. return
  45. }
  46. // Convert params to reflect.Value
  47. paramsValue := make([]reflect.Value, len(params))
  48. for i, param := range params {
  49. paramsValue[i] = reflect.ValueOf(param)
  50. }
  51. // Call the function f with params
  52. funcValue.Call(paramsValue)
  53. }()
  54. }