diff --git a/.vscode/launch.json b/.vscode/launch.json index 8e7ace7..a0ec5ce 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -4,9 +4,17 @@ // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ - { - "name": "Launch Package", + "name": "server", + "type": "go", + "request": "launch", + "mode": "auto", + "args": ["-document-root", "${workspaceFolder}/env"], + "console": "integratedTerminal", + "program": "${workspaceFolder}/cmd/server" + }, + { + "name": "cli", "type": "go", "request": "launch", "mode": "auto", diff --git a/cmd/server/api/api.go b/cmd/server/api/api.go index a08a068..74c0c5c 100644 --- a/cmd/server/api/api.go +++ b/cmd/server/api/api.go @@ -3,12 +3,9 @@ package api import ( "cloudsave/cmd/server/data" "cloudsave/pkg/repository" - "crypto/md5" - "encoding/hex" "encoding/json" "errors" "fmt" - "io" "log/slog" "net/http" "os" @@ -343,41 +340,19 @@ func (s HTTPServer) histExists(w http.ResponseWriter, r *http.Request) { func (s HTTPServer) hash(w http.ResponseWriter, r *http.Request) { id := chi.URLParam(r, "id") - path := filepath.Clean(filepath.Join(s.documentRoot, "data", id)) - sdir, err := os.Stat(path) + sum, err := data.Hash(id, s.documentRoot) if err != nil { - notFound("id not found", w, r) - return - } - - if !sdir.IsDir() { - notFound("id not found", w, r) - return - } - - path = filepath.Join(path, "data.tar.gz") - - f, err := os.OpenFile(path, os.O_RDONLY, 0) - if err != nil { - notFound("id not found", w, r) - return - } - defer f.Close() - - // Create MD5 hasher - hasher := md5.New() - - // Copy file content into hasher - if _, err := io.Copy(hasher, f); err != nil { - fmt.Fprintln(os.Stderr, "error: an error occured while reading data:", err) + if errors.Is(err, data.ErrNotExists) { + notFound("id not found", w, r) + return + } + fmt.Fprintln(os.Stderr, "error: an error occured while calculating the hash:", err) internalServerError(w, r) return } - // Get checksum result - sum := hasher.Sum(nil) - ok(hex.EncodeToString(sum), w, r) + ok(sum, w, r) } func (s HTTPServer) metadata(w http.ResponseWriter, r *http.Request) { diff --git a/cmd/server/data/data.go b/cmd/server/data/data.go index 19fc9ba..1a99804 100644 --- a/cmd/server/data/data.go +++ b/cmd/server/data/data.go @@ -23,6 +23,7 @@ type ( var ( ErrBackupNotExists error = errors.New("backup not found") + ErrNotExists error = errors.New("not found") // singleton hashCacheMu sync.RWMutex @@ -175,6 +176,9 @@ func Hash(gameID, documentRoot string) (string, error) { sdir, err := os.Stat(path) if err != nil { + if errors.Is(err, os.ErrNotExist) { + return "", ErrNotExists + } return "", err }