github.com/wangyougui/gf/v2@v2.6.5/debug/gdebug/gdebug_version.go (about)

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