gdebug_version.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. // Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
  2. //
  3. // This Source Code Form is subject to the terms of the MIT License.
  4. // If a copy of the MIT was not distributed with this file,
  5. // You can obtain one at https://github.com/gogf/gf.
  6. package gdebug
  7. import (
  8. "crypto/md5"
  9. "fmt"
  10. "io"
  11. "os"
  12. "strconv"
  13. "github.com/gogf/gf/v2/encoding/ghash"
  14. "github.com/gogf/gf/v2/errors/gerror"
  15. )
  16. // BinVersion returns the version of current running binary.
  17. // It uses ghash.BKDRHash+BASE36 algorithm to calculate the unique version of the binary.
  18. func BinVersion() string {
  19. if binaryVersion == "" {
  20. binaryContent, _ := os.ReadFile(selfPath)
  21. binaryVersion = strconv.FormatInt(
  22. int64(ghash.BKDR(binaryContent)),
  23. 36,
  24. )
  25. }
  26. return binaryVersion
  27. }
  28. // BinVersionMd5 returns the version of current running binary.
  29. // It uses MD5 algorithm to calculate the unique version of the binary.
  30. func BinVersionMd5() string {
  31. if binaryVersionMd5 == "" {
  32. binaryVersionMd5, _ = md5File(selfPath)
  33. }
  34. return binaryVersionMd5
  35. }
  36. // md5File encrypts file content of `path` using MD5 algorithms.
  37. func md5File(path string) (encrypt string, err error) {
  38. f, err := os.Open(path)
  39. if err != nil {
  40. err = gerror.Wrapf(err, `os.Open failed for name "%s"`, path)
  41. return "", err
  42. }
  43. defer f.Close()
  44. h := md5.New()
  45. _, err = io.Copy(h, f)
  46. if err != nil {
  47. err = gerror.Wrap(err, `io.Copy failed`)
  48. return "", err
  49. }
  50. return fmt.Sprintf("%x", h.Sum(nil)), nil
  51. }