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

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