gdebug_version.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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. "io/ioutil"
  12. "os"
  13. "strconv"
  14. "github.com/gogf/gf/v2/encoding/ghash"
  15. "github.com/gogf/gf/v2/errors/gerror"
  16. )
  17. // BinVersion returns the version of current running binary.
  18. // It uses ghash.BKDRHash+BASE36 algorithm to calculate the unique version of the binary.
  19. func BinVersion() string {
  20. if binaryVersion == "" {
  21. binaryContent, _ := ioutil.ReadFile(selfPath)
  22. binaryVersion = strconv.FormatInt(
  23. int64(ghash.BKDR(binaryContent)),
  24. 36,
  25. )
  26. }
  27. return binaryVersion
  28. }
  29. // BinVersionMd5 returns the version of current running binary.
  30. // It uses MD5 algorithm to calculate the unique version of the binary.
  31. func BinVersionMd5() string {
  32. if binaryVersionMd5 == "" {
  33. binaryVersionMd5, _ = md5File(selfPath)
  34. }
  35. return binaryVersionMd5
  36. }
  37. // md5File encrypts file content of `path` using MD5 algorithms.
  38. func md5File(path string) (encrypt string, err error) {
  39. f, err := os.Open(path)
  40. if err != nil {
  41. err = gerror.Wrapf(err, `os.Open failed for name "%s"`, path)
  42. return "", err
  43. }
  44. defer f.Close()
  45. h := md5.New()
  46. _, err = io.Copy(h, f)
  47. if err != nil {
  48. err = gerror.Wrap(err, `io.Copy failed`)
  49. return "", err
  50. }
  51. return fmt.Sprintf("%x", h.Sum(nil)), nil
  52. }