如何獲取文件的md5和sha256值

 閱讀大約需要3分鐘

golang實現代碼cobra_study.go如下:

package main

import (
    "crypto/md5"
    "crypto/sha256"
    "fmt"
    "github.com/mitchellh/go-homedir"
    "github.com/spf13/cobra"
    "github.com/spf13/viper"
    "io"
    "log"
    "os"
)

var cfgFile string
var md5Str string
var sha256Str string

func getFileSha256(path string) string {
    f, err := os.Open(path)
    if err != nil {
        log.Fatal(err)
    }
    defer f.Close()

    h := sha256.New()
    if _, err := io.Copy(h, f); err != nil {
        log.Fatal(err)
    }

    return fmt.Sprintf("%x\n", h.Sum(nil))
}

func getFileMd5(path string) string {
    f, err := os.Open(path)
    if err != nil {
        log.Fatal(err)
    }
    defer f.Close()

    h := md5.New()
    if _, err := io.Copy(h, f); err != nil {
        log.Fatal(err)
    }

    return fmt.Sprintf("%x\n", h.Sum(nil))
}

// rootCmd represents the base command when called without any subcommands
var rootCmd = &cobra.Command{
    Use: "cobra_study",
    Short: "A brief description of your application",
    Long: `get file md5 and sha256 value`,
    // Uncomment the following line if your bare application
    // has an action associated with it:
    Run: func(cmd *cobra.Command, args []string) {
        if len(md5Str) > 0 {
            r := getFileMd5(md5Str)
            fmt.Printf("get file %s md5 value is \n%s", md5Str, r)
        }

        if len(sha256Str) > 0 {
            r := getFileSha256(sha256Str)
            fmt.Printf("get file %s sha256 value is \n%s", sha256Str, r)
        }

    },
}

// Execute adds all child commands to the root command and sets flags appropriately.
// This is called by main.main(). It only needs to happen once to the rootCmd.
func Execute() {
    if err := rootCmd.Execute(); err != nil {
        fmt.Println(err)
        os.Exit(1)
    }
}

func init() {
    cobra.OnInitialize(initConfig)

    // Here you will define your flags and configuration settings.
    // Cobra supports persistent flags, which, if defined here,
    // will be global for your application.

    rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file")

    // Cobra also supports local flags, which will only run
    // when this action is called directly.
    //rootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
    rootCmd.Flags().StringVar(&md5Str, "md5", "", "input file name get md5 value")
    rootCmd.Flags().StringVar(&sha256Str, "sha256", "", "input file name get sha256 value")

}

// initConfig reads in config file and ENV variables if set.
func initConfig() {
    if cfgFile != "" {
        // Use config file from the flag.
        viper.SetConfigFile(cfgFile)
    } else {
        // Find home directory.
        home, err := homedir.Dir()
        if err != nil {
            fmt.Println(err)
            os.Exit(1)
        }

        // Search config in home directory with name ".yingzhou.online" (without extension).
        viper.AddConfigPath(home)
        viper.SetConfigName(".cobra_study")
    }

    viper.AutomaticEnv() // read in environment variables that match

    // If a config file is found, read it in.
    if err := viper.ReadInConfig(); err == nil {
        fmt.Println("Using config file:", viper.ConfigFileUsed())
    }
}

func main() {
    Execute()
}

編譯go build cobra_study.go

在命令行執行如下:

$ ./cobra_study -h
get file md5 and sha256 value

Usage:
  cobra_study [flags]

Flags:
      --config string config file
  -h, --help help for cobra_study
      --md5 string input file name get md5 value
      --sha256 string input file name get sha256 value

獲取list.html的md5值

$ ./cobra_study --md5 list.html
get file list.html md5 value is
643418ee611bced1b26f9bf6e90d8b32

獲取list.html的sha256值

$ ./cobra_study --sha256 list.html
get file list.html sha256 value is
1d3ee98f0b7fe40ef640e5017b48a48fcc1cf6b7dbdf12049f2687197e589459