高热共公日志库
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.

76 lines
1.7 KiB

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