Ver Fonte

moving hash file to package hash

Klaas, Wilfried há 2 anos atrás
pai
commit
5b9b929864
2 ficheiros alterados com 21 adições e 20 exclusões
  1. 2 19
      cmd/main.go
  2. 19 1
      pkg/hash/hash.go

+ 2 - 19
cmd/main.go

@@ -2,11 +2,8 @@ package main
 
 import (
 	"bufio"
-	"crypto/sha256"
-	"encoding/hex"
 	"encoding/json"
 	"fmt"
-	"io"
 	"io/ioutil"
 	"log"
 	"os"
@@ -75,26 +72,12 @@ func main() {
 			saveAllHashFiles()
 		}
 	} else {
-		log.Printf("file %s has hash %s\n", myFile, getSha256Hash(myFile))
+		log.Printf("file %s has hash %s\n", myFile, hash.GetFileHash(myFile))
 	}
 
 	log.Println("done")
 }
 
-func getSha256Hash(fileStr string) string {
-	f, err := os.Open(fileStr)
-	if err != nil {
-		log.Fatal(err)
-	}
-	defer f.Close()
-
-	h := sha256.New()
-	if _, err := io.Copy(h, f); err != nil {
-		log.Fatal(err)
-	}
-	return hex.EncodeToString(h.Sum(nil))
-}
-
 var lock1 = sync.RWMutex{}
 var lock2 = sync.RWMutex{}
 
@@ -135,7 +118,7 @@ func calculateHash(fileStr string) {
 	}
 	if doHash {
 		log.Printf("starting %s\n", fileStr)
-		hash := getSha256Hash(fileStr)
+		hash := hash.GetFileHash(fileStr)
 		log.Printf("ready %s\n", fileStr)
 		mu.Lock()
 		lock1.Lock()

+ 19 - 1
pkg/hash/hash.go

@@ -1,8 +1,12 @@
 package hash
 
 import (
+	"crypto/sha256"
+	"encoding/hex"
 	"encoding/json"
+	"io"
 	"io/ioutil"
+	"log"
 	"os"
 	"path/filepath"
 	"strings"
@@ -74,6 +78,20 @@ func GetHash(path string, name string) (string, error) {
 		fdHashes = *fh
 	}
 
-	hash, _ := fdHashes.Hashes[name]
+	hash := fdHashes.Hashes[name]
 	return hash, nil
 }
+
+func GetFileHash(fileStr string) string {
+	f, err := os.Open(fileStr)
+	if err != nil {
+		log.Fatal(err)
+	}
+	defer f.Close()
+
+	h := sha256.New()
+	if _, err := io.Copy(h, f); err != nil {
+		log.Fatal(err)
+	}
+	return hex.EncodeToString(h.Sum(nil))
+}