高热共公日志库
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

62 lines
1.6 KiB

  1. package grlogs
  2. //传入一个字符串,返回一个加密后的md5
  3. func Md5(str string) string {
  4. data := []byte(str)
  5. has := md5.Sum(data)
  6. md5str := fmt.Sprintf("%x", has) //将[]byte转成16进制
  7. return md5str
  8. }
  9. func Md5File(filePath string) string {
  10. hash := md5.New()
  11. data, _ := ioutil.ReadFile(filePath)
  12. hash.Write([]byte(data))
  13. md5str := hex.EncodeToString(hash.Sum(nil))
  14. return md5str
  15. }
  16. func GetPackageName() string {
  17. packpath := reflect.TypeOf(Empty{}).PkgPath()
  18. if idx := strings.Index(packpath, "/"); idx > 0 {
  19. return packpath[:idx]
  20. } else {
  21. return packpath
  22. }
  23. }
  24. func GetCwd(filepath ...string) string {
  25. _, filename1, _, _ := runtime.Caller(0)
  26. filename2, _ := os.Getwd()
  27. if !strings.HasSuffix(filename2, GetPackageName()) {
  28. paths := append([]string{path.Dir(filename1), "/../../"}, filepath...)
  29. return path.Join(paths...)
  30. } else {
  31. paths := append([]string{filename2, "/"}, filepath...)
  32. return path.Join(paths...)
  33. }
  34. }
  35. func SetCwd() error {
  36. _, filename1, _, _ := runtime.Caller(0)
  37. filename2, _ := os.Getwd()
  38. if !strings.HasSuffix(filename2, GetPackageName()) {
  39. paths := append([]string{path.Dir(filename1), "/../../"})
  40. return os.Chdir(path.Join(paths...))
  41. } else {
  42. paths := append([]string{filename2, "/"})
  43. return os.Chdir(path.Join(paths...))
  44. }
  45. }
  46. func RandString(length int) string {
  47. str := "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
  48. bytes := []byte(str)
  49. result := []byte{}
  50. r := rand.New(rand.NewSource(time.Now().UnixNano()))
  51. for i := 0; i < length; i++ {
  52. result = append(result, bytes[r.Intn(len(bytes))])
  53. }
  54. return string(result)
  55. }