diff options
author | Baitinq <manuelpalenzuelamerino@gmail.com> | 2024-05-27 21:30:54 +0200 |
---|---|---|
committer | Baitinq <manuelpalenzuelamerino@gmail.com> | 2024-05-27 23:52:44 +0200 |
commit | 81621c4f64f4a1c29906643f53314e2f71a014ae (patch) | |
tree | 503cc56b609dcad8f8eca6e64b6b9b15b02fd4fd /src/rest-api/handler/handler.go | |
parent | payload-processor: fmt (diff) | |
download | fs-tracer-backend-81621c4f64f4a1c29906643f53314e2f71a014ae.tar.gz fs-tracer-backend-81621c4f64f4a1c29906643f53314e2f71a014ae.tar.bz2 fs-tracer-backend-81621c4f64f4a1c29906643f53314e2f71a014ae.zip |
rest-api: connect to db and add /file/ GET endpoint
TODO: Only get files for your specific user
Diffstat (limited to 'src/rest-api/handler/handler.go')
-rw-r--r-- | src/rest-api/handler/handler.go | 38 |
1 files changed, 37 insertions, 1 deletions
diff --git a/src/rest-api/handler/handler.go b/src/rest-api/handler/handler.go index 9e44612..558e773 100644 --- a/src/rest-api/handler/handler.go +++ b/src/rest-api/handler/handler.go @@ -6,22 +6,58 @@ import ( "io" "log" "net/http" + "strings" "time" + "github.com/jmoiron/sqlx" + _ "github.com/lib/pq" "github.com/segmentio/kafka-go" ) type Handler struct { + db DB kafka_writer *kafka.Writer } -func NewHandler(kafka_writer *kafka.Writer) Handler { +func NewHandler(db *sqlx.DB, kafka_writer *kafka.Writer) Handler { return Handler{ + db: NewDB(db), kafka_writer: kafka_writer, } } func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { + switch r.Method { + case http.MethodGet: + h.handleGet(w, r) + case http.MethodPost: + h.handlePost(w, r) + default: + http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) + } +} + +func (h Handler) handleGet(w http.ResponseWriter, r *http.Request) { + _, filePath, ok := strings.Cut(r.URL.Path, "/file/") + if !ok { + http.Error(w, "Invalid file path", http.StatusBadRequest) + return + } + + log.Println("File path: ", filePath) + + ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second) + defer cancel() + file, err := h.db.GetLatestFileByPath(ctx, filePath) + if err != nil { + http.Error(w, fmt.Sprintf("Internal server error: %s", err), http.StatusInternalServerError) + return + } + + fmt.Fprintln(w, "File: ", file) +} + +func (h Handler) handlePost(w http.ResponseWriter, r *http.Request) { bytes, err := io.ReadAll(io.Reader(r.Body)) if err != nil { log.Fatal(err) |