From 82d5136c1b03efbb99931884dd75ab1160689ceb Mon Sep 17 00:00:00 2001 From: Saumit Dinesan Date: Tue, 28 Nov 2023 15:17:18 +0530 Subject: Refactoring project - Introducing handlers,models and utils- Updating previous hasher and idgen func + formatting --- handlers/handlers.go | 75 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 75 insertions(+) create mode 100644 handlers/handlers.go (limited to 'handlers/handlers.go') diff --git a/handlers/handlers.go b/handlers/handlers.go new file mode 100644 index 0000000..f350589 --- /dev/null +++ b/handlers/handlers.go @@ -0,0 +1,75 @@ +package handlers + +import ( + "database/sql" + "github.com/justsaumit/go-fis-api/models" + "github.com/justsaumit/go-fis-api/utils" + "github.com/labstack/echo/v4" + _ "github.com/mattn/go-sqlite3" + "log" + "net/http" +) + +var db *sql.DB + +func init() { + var err error + db, err = sql.Open("sqlite3", "hashstore.db") + if err != nil { + log.Fatalf("sqlite3 not installed: %v", err) + } + + if err = db.Ping(); err != nil { + log.Fatalf("Failed to connect to database: %v", err) + } + + // Create the 'hashes' table if it does not exist + _, err = db.Exec(` + CREATE TABLE IF NOT EXISTS hashes ( + ID TEXT PRIMARY KEY, + HashValue TEXT NOT NULL + ); + `) +} + +// AddHash handles the file upload, store and response +func AddHash(c echo.Context) error { + file, err := c.FormFile("file") + if err != nil { + log.Println("Failed to bind request:", err) + return c.JSON(http.StatusBadRequest, map[string]string{"message": "Invalid request"}) + } + + src, err := file.Open() + if err != nil { + log.Println("Failed to Open File", err) + return err + } + defer src.Close() + + id, err := utils.GenerateID() + if err != nil { + log.Println("Failed to Generate ID", err) + } + + hash, err := utils.GenerateHash(src) + if err != nil { + log.Println("Failed to Generate Hash", err) + } + + // Store id and hash in the database + _, err := db.Exec("INSERT INTO hashes (ID, HashValue) VALUES (?, ?)", id, hash) + if err != nil { + log.Println("Failed to insert into database:", err) + //return c.JSON(http.StatusInternalServerError, map[string]string{"message": "Failed to store hash"}) + } + //return c.JSON(http.StatusOK, map[string]string{"id": id, "message": "Hash added successfully"}) + + data := models.FileHashPair{ + ID: id, + FileHash: hash, + } + + log.Println("Hash added successfully") + return c.JSON(http.StatusOK, data) +} -- cgit v1.2.3