Skip to content

Commit

Permalink
feat: proper error messages and updating the last/access count when
Browse files Browse the repository at this point in the history
successfully redirect to the original URL
  • Loading branch information
Hamza12700 committed Sep 12, 2024
1 parent 28fdecf commit 96bba44
Showing 1 changed file with 33 additions and 20 deletions.
53 changes: 33 additions & 20 deletions handlers/redirection.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,36 +4,49 @@ import (
"database/sql"
"log"
"net/http"
"time"

"github.com/wavly/shawty/database"
)

func Redirection(w http.ResponseWriter, r *http.Request) {
// Truncate the route `/shawty/` from path
slug := r.URL.Path[8:]
// Get the URL-Path slug "url"
code := r.PathValue("code")

db := database.ConnectDB()
defer db.Close()

var code string
var originalUrl string

// Get the url for the slug if exist
row := db.QueryRow("SELECT code, original_url FROM urls WHERE code = ?", slug)
result := row.Scan(&code, &originalUrl)

if result == sql.ErrNoRows {
w.Write([]byte("Couldn't find anything in your shawty, recheck..\n"))
} else if result != nil {
http.Error(w, "Sorry, an unexpected error occur while fetching full URL", http.StatusInternalServerError)
log.Println("Failed to fetch original_url", result)
} else {
http.Redirect(w, r, originalUrl, http.StatusFound)

// If url exists, update accessed count and last accessed time. after recirecting
_, err := db.Exec("UPDATE urls SET accessed_count = accessed_count + 1, last_accessed = CURRENT_TIMESTAMP WHERE code = ?", slug)
if err != nil {
log.Println("Failed to update URL's accessed_count, last_accessed", err)
row := db.QueryRow("select original_url from urls where code = ?", code)
var originalUrl string
if err := row.Scan(&originalUrl); err != nil {
if err != sql.ErrNoRows {
http.Error(w, "Sorry, an unexpected error occur when querying the database", http.StatusInternalServerError)
log.Println("Failed to retrive original_url from the database:", err)
return
}

w.WriteHeader(http.StatusNotFound)
w.Write([]byte("404 not found, try again"))
return
}

// Update the accessed_count
_, err := db.Exec("update urls set accessed_count = accessed_count + 1 where code = ?", code)
if err != nil {
http.Error(w, "Sorry, an unexpected error occur when updating the access count from the database", http.StatusInternalServerError)
log.Println("Failed to update the accessed_count from the database:", err)
return
}

// Update the last_accessed
_, err = db.Exec("update urls set last_accessed = ?", time.Now().UTC())
if err != nil {
http.Error(w, "Sorry, an unexpected error occur when updating the last_accessed count from the database", http.StatusInternalServerError)
log.Println("Failed to update the last_accessed from the database:", err)
return
}

// Redirect to original URL
http.Redirect(w, r, originalUrl, http.StatusFound)
}

0 comments on commit 96bba44

Please sign in to comment.