summaryrefslogtreecommitdiff
path: root/handlers/handlers.go
diff options
context:
space:
mode:
authorSaumit Dinesan <justsaumit@protonmail.com>2023-11-28 15:17:18 +0530
committerSaumit Dinesan <justsaumit@protonmail.com>2023-11-28 15:17:18 +0530
commit82d5136c1b03efbb99931884dd75ab1160689ceb (patch)
tree3095f344055c4ad54a8238599839fa0088054fbd /handlers/handlers.go
parenta3ead3d67520704eda55a74841b00d5766728fab (diff)
Refactoring project - Introducing handlers,models and utils- Updating previous hasher and idgen func + formatting
Diffstat (limited to 'handlers/handlers.go')
-rw-r--r--handlers/handlers.go75
1 files changed, 75 insertions, 0 deletions
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)
+}