Skip to content

Commit

Permalink
Refactor main.go to improve file transfer handling and add API endpoint
Browse files Browse the repository at this point in the history
  • Loading branch information
abdealijaroli committed Oct 5, 2024
1 parent 2047d00 commit 09b7255
Showing 1 changed file with 3 additions and 55 deletions.
58 changes: 3 additions & 55 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,18 +5,12 @@ import (
"net/http"
"os"

"github.com/abdealijaroli/jaro/api"
"github.com/abdealijaroli/jaro/cmd"
"github.com/abdealijaroli/jaro/cmd/stream"
"github.com/abdealijaroli/jaro/store"
"github.com/gorilla/websocket"
)

var upgrader = websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool {
return true // Allow all origins for this example
},
}

func main() {
storage, err := store.NewPostgresStore()
if err != nil {
Expand All @@ -31,55 +25,9 @@ func main() {
fs := http.FileServer(http.Dir("web/public"))
http.Handle("/public/", http.StripPrefix("/public/", fs))

http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
shortCode := r.URL.Path[1:]
if shortCode == "" {
http.ServeFile(w, r, "web/index.html")
return
}
originalURL, err := storage.GetOriginalURL(shortCode)
if err != nil {
http.Error(w, "four oh four - not found :(", http.StatusNotFound)
return
}
isFileTransfer, err := storage.CheckFileTransfer(shortCode)
if err != nil {
http.Error(w, "four oh four - not found :(", http.StatusNotFound)
return
}
if isFileTransfer {
http.ServeFile(w, r, "web/receiver.html")
return
}
http.Redirect(w, r, originalURL, http.StatusFound)
})

http.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) {
roomID := r.URL.Query().Get("room")
if roomID == "" {
http.Error(w, "Missing room ID", http.StatusBadRequest)
return
}

// Upgrade HTTP connection to WebSocket
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Printf("Error upgrading to WebSocket: %v", err)
return
}
defer conn.Close()

//Retrieve the file path associated with this room ID from your database
filePath, err := storage.GetOriginalURL(roomID)
if err != nil {
log.Printf("Error getting file path for room %s: %v", roomID, err)
conn.WriteMessage(websocket.TextMessage, []byte("Error: File not found"))
return
}
http.HandleFunc("/", api.HandleGetAndRedirect(storage))

// Initiate the file transfer
stream.HandleTransferRequest(conn, filePath)
})
http.HandleFunc("/ws", stream.InitiateTransfer(storage))

if len(os.Args) > 1 {
cmd.Execute()
Expand Down

0 comments on commit 09b7255

Please sign in to comment.