diff --git a/internal/db/database.go b/internal/db/database.go index 27f8c5e..ada3568 100644 --- a/internal/db/database.go +++ b/internal/db/database.go @@ -14,6 +14,20 @@ type Database struct { client *pgx.Conn } +type URL struct { + ShortURL string `json:"shorturl"` + URL string `json:"url"` + ExpiresAt time.Time `json:"expires_at"` +} + +type PageVisit struct { + ShortURL string `json:"shorturl"` + Count int `json:"count"` + IP_Address string `json:"ip_address"` + UserAgent string `json:"user_agent"` + CreatedAt time.Time `json:"created_at"` +} + func NewDatabaseClient(config utils.DatabaseConfig) (*Database, error) { conn, err := pgx.Connect(context.Background(), utils.DatabaseUrl()) if err != nil { @@ -24,15 +38,47 @@ func NewDatabaseClient(config utils.DatabaseConfig) (*Database, error) { return &Database{client: conn}, nil } -func (d *Database) InsertNewURL(shorturl string, url string) error { +func (d *Database) InsertNewURL(u URL) error { + fmt.Print("InsertNewURL called with URL: ", u.URL) timeNow := time.Now() - _, err := d.client.Exec(context.Background(), "INSERT INTO urls (shorturl, url, created_at) VALUES ($1, $2, $3)", shorturl, url, timeNow) + _, err := d.client.Exec(context.Background(), "INSERT INTO urls (shorturl, url, created_at,expires_at,active) VALUES ($1, $2, $3,$4,$5)", u.ShortURL, u.URL, timeNow, u.ExpiresAt, true) if err != nil { return fmt.Errorf("failed to insert URL into database: %w", err) } return nil } +func (d *Database) InsertAnalytics(p PageVisit) error { + timeNow := time.Now() + _, err := d.client.Exec(context.Background(), "INSERT INTO analytics (shorturl, count, ip_address, user_agent, created_at) VALUES ($1, $2, $3, $4, $5)", p.ShortURL, p.Count, p.IP_Address, p.UserAgent, timeNow) + if err != nil { + return fmt.Errorf("failed to insert analytics into database: %w", err) + } + return nil +} + +func (d *Database) GetAnalytics(shorturl string) ([]PageVisit, error) { + rows, err := d.client.Query(context.Background(), "SELECT shorturl, count, ip_address, user_agent, created_at FROM analytics WHERE shorturl = $1", shorturl) + if err != nil { + return nil, fmt.Errorf("failed to retrieve analytics from database: %w", err) + } + defer rows.Close() + + var analytics []PageVisit + for rows.Next() { + var p PageVisit + err := rows.Scan(&p.ShortURL, &p.Count, &p.IP_Address, &p.UserAgent, &p.CreatedAt) + if err != nil { + return nil, fmt.Errorf("failed to scan analytics row: %w", err) + } + analytics = append(analytics, p) + } + if err := rows.Err(); err != nil { + return nil, fmt.Errorf("error iterating over analytics rows: %w", err) + } + return analytics, nil +} + func (d *Database) DeleteURL(shorturl string) error { _, err := d.client.Exec(context.Background(), "DELETE FROM urls WHERE shorturl = $1", shorturl) if err != nil { diff --git a/internal/db/migrations/20250806_initial.sql b/internal/db/migrations/20250806_initial.sql new file mode 100644 index 0000000..a418f4d --- /dev/null +++ b/internal/db/migrations/20250806_initial.sql @@ -0,0 +1,20 @@ +CREATE TABLE urls ( + shorturl VARCHAR(7) PRIMARY KEY, + url VARCHAR(100) NOT NULL, + created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + expires_at TIMESTAMP DEFAULT NULL, + active BOOLEAN DEFAULT TRUE + +); + +CREATE TABLE analytics ( + id BIGINT AUTO_INCREMENT PRIMARY KEY, + shorturl VARCHAR(7) NOT NULL, + count INTEGER DEFAULT 0, + ip_address VARCHAR(50) DEFAULT NULL, + user_agent VARCHAR(1024) DEFAULT NULL, + created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + + FOREIGN KEY (shorturl) REFERENCES urls(shorturl), + +); diff --git a/internal/shortener/handler.go b/internal/shortener/handler.go index 53c5de5..9590699 100644 --- a/internal/shortener/handler.go +++ b/internal/shortener/handler.go @@ -1,12 +1,15 @@ package shortener import ( + "context" + "encoding/json" "fmt" "net/http" + "sync" + "time" "github.com/ferdzo/ferurl/internal/cache" "github.com/ferdzo/ferurl/internal/db" - "github.com/ferdzo/ferurl/utils" "github.com/go-chi/chi/v5" ) @@ -18,6 +21,7 @@ type Service struct { type Handler struct { service *Service + baseURL string } func NewService(redisConfig utils.RedisConfig, databaseConfig utils.DatabaseConfig) (*Service, error) { @@ -33,17 +37,37 @@ func NewService(redisConfig utils.RedisConfig, databaseConfig utils.DatabaseConf return &Service{cache: redisClient, database: databaseClient}, nil } -func NewHandler(service *Service) (*Handler, error) { +func NewHandler(service *Service, baseURL string) (*Handler, error) { if service == nil { return nil, fmt.Errorf("service is nil") } - return &Handler{service: service}, nil + return &Handler{service: service, baseURL: baseURL}, nil } - func (h *Handler) CreateShortURL(w http.ResponseWriter, r *http.Request) { - longUrl := r.FormValue("url") + w.Header().Set("Access-Control-Allow-Origin", "*") + w.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS") + w.Header().Set("Access-Control-Allow-Headers", "Content-Type") + if r.Method == "OPTIONS" { + w.WriteHeader(http.StatusOK) + return + } + + w.Header().Set("Content-Type", "application/json") + + var input struct { + URL string `json:"url"` + ExpiresAt time.Time `json:"expires_at"` + } + + decoder := json.NewDecoder(r.Body) + if err := decoder.Decode(&input); err != nil { + http.Error(w, "Invalid JSON input", http.StatusBadRequest) + return + } + + longUrl := input.URL if longUrl == "" { http.Error(w, "Long URL is required", http.StatusBadRequest) return @@ -52,26 +76,75 @@ func (h *Handler) CreateShortURL(w http.ResponseWriter, r *http.Request) { http.Error(w, "Invalid URL", http.StatusBadRequest) return } + expiresAt := input.ExpiresAt shortUrl := generateShortUrl(longUrl) + fetchedShortUrl, _ := h.fetchUrl(shortUrl) + if fetchedShortUrl != "" { + fullShortUrl := fmt.Sprintf("%s%s", h.baseURL, shortUrl) + json.NewEncoder(w).Encode(map[string]string{"short_url": fullShortUrl}) + return + } + + newUrl := db.URL{ + URL: longUrl, + ShortURL: shortUrl, + ExpiresAt: expiresAt, + } + + if err := h.service.storeUrl(newUrl); err != nil { + fmt.Println(err) + http.Error(w, "Internal Server Error", http.StatusInternalServerError) + return + } + + fullShortUrl := fmt.Sprintf("%s%s", h.baseURL, shortUrl) + json.NewEncoder(w).Encode(map[string]string{"short_url": fullShortUrl}) - http.Redirect(w, r, shortUrl, http.StatusSeeOther) } func (h *Handler) GetUrl(w http.ResponseWriter, r *http.Request) { - id := chi.URLParam(r, "key") - if id == "" { + w.Header().Set("Access-Control-Allow-Origin", "*") + w.Header().Set("Access-Control-Allow-Methods", "GET, OPTIONS") + + if r.Method == "OPTIONS" { + w.WriteHeader(http.StatusOK) + return + } + shortKey := chi.URLParam(r, "key") + if shortKey == "" { http.Error(w, "ID is required", http.StatusBadRequest) return } - shortUrl, err := h.fetchUrl(id) - if err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) + if !utils.IsValidShortUrl(shortKey) { + http.Error(w, "Invalid short URL", http.StatusBadRequest) return } - http.Redirect(w, r, shortUrl, http.StatusSeeOther) + longUrl, err := h.fetchUrl(shortKey) + if err != nil { + fmt.Println(err) + http.Error(w, "URL not found", http.StatusInternalServerError) + return + } + + pv := db.PageVisit{ + ShortURL: shortKey, + Count: 1, + IP_Address: r.RemoteAddr, + UserAgent: r.UserAgent(), + CreatedAt: time.Now(), + } + + err = h.service.database.InsertAnalytics(pv) + if err != nil { + fmt.Println(err) + http.Error(w, "Internal Server Error", http.StatusInternalServerError) + return + } + + http.Redirect(w, r, longUrl, http.StatusSeeOther) } func generateShortUrl(url string) string { @@ -81,13 +154,66 @@ func generateShortUrl(url string) string { } func (h *Handler) fetchUrl(id string) (string, error) { - if url, err := h.service.fetchUrlFromCache(id); err == nil { - return url, nil + type result struct { + url string + err error + source string } - if url, err := h.service.fetchUrlFromDatabase(id); err == nil { - return url, nil + resultChan := make(chan result, 2) + + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + go func() { + url, err := h.service.fetchUrlFromCache(id) + select { + case resultChan <- result{url, err, "cache"}: + case <-ctx.Done(): + return + } + }() + + go func() { + url, err := h.service.fetchUrlFromDatabase(id) + select { + case resultChan <- result{url, err, "db"}: + case <-ctx.Done(): + return + } + }() + + var foundInDB string + var cacheHit bool + var lastErr error + + for range 2 { + res := <-resultChan + if res.err == nil { + if res.source == "db" { + foundInDB = res.url + if !cacheHit { + continue + } + } else if res.source == "cache" { + cacheHit = true + if foundInDB != "" { + return res.url, nil + } + } + + return res.url, nil + } + lastErr = res.err } - return "", fmt.Errorf("URL not found") + + if foundInDB != "" { + go func() { + _ = h.service.cache.Set(id, foundInDB) + fmt.Println("URL updated in Redis") + }() + return foundInDB, nil + } + + return "", lastErr } func (s *Service) fetchUrlFromCache(shortUrl string) (string, error) { @@ -97,9 +223,42 @@ func (s *Service) fetchUrlFromCache(shortUrl string) (string, error) { return "", fmt.Errorf("URL not found") } -func (s *Service) fetchUrlFromDatabase(id string) (string, error) { - if url, err := s.database.GetURL(id); err == nil { +func (s *Service) fetchUrlFromDatabase(shortUrl string) (string, error) { + if url, err := s.database.GetURL(shortUrl); err == nil { return url, nil } + return "", fmt.Errorf("URL not found") } + +func (s *Service) storeUrl(u db.URL) error { + var wg sync.WaitGroup + errChan := make(chan error, 2) + + wg.Add(1) + go func() { + defer wg.Done() + if err := s.cache.Set(u.ShortURL, u.URL); err != nil { + errChan <- err + } + }() + + wg.Add(1) + go func() { + defer wg.Done() + if err := s.database.InsertNewURL(u); err != nil { + errChan <- err + } + }() + + go func() { + wg.Wait() + close(errChan) + }() + + for err := range errChan { + return err + } + + return nil +} diff --git a/main.go b/main.go index 2e406f2..f0ed4e9 100644 --- a/main.go +++ b/main.go @@ -13,41 +13,36 @@ import ( func main() { fmt.Println("Welcome to ferurl, a simple URL shortener!") - redisConfig, err := utils.LoadRedisConfig() - if err != nil { - fmt.Println("Error loading Redis config:", err) - return - } - dbConfig, err := utils.LoadDbConfig() - if err != nil { - fmt.Println("Error loading DB config:", err) - return - } + redisConfig := utils.LoadRedisConfig() + dbConfig := utils.LoadDbConfig() s, err := shortner.NewService(redisConfig, dbConfig) if err != nil { fmt.Println("Error creating service:", err) return } - - h, err := shortner.NewHandler(s) + baseUrl := utils.GetEnv("BASE_URL", "https://url.ferdzo.xyz") + h, err := shortner.NewHandler(s, baseUrl) if err != nil { fmt.Println("Error creating handler:", err) return } + initServer(*h) } func initServer(h shortner.Handler) { r := chi.NewRouter() r.Use(middleware.Logger) + r.Get("/", func(w http.ResponseWriter, r *http.Request) { + http.ServeFile(w, r, "./web/index.html") + }) r.Get("/health", func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "Welcome to ferurl!") }) fmt.Println("Server started on port 3000") r.Post("/create", h.CreateShortURL) r.Get("/{key}", h.GetUrl) - http.FileServer(http.Dir("web")) http.ListenAndServe(":3000", r) } diff --git a/utils/utils.go b/utils/utils.go index 3534b5c..2c36f51 100644 --- a/utils/utils.go +++ b/utils/utils.go @@ -23,3 +23,16 @@ func IsValidUrl(s string) bool { return true } + +func IsValidShortUrl(s string) bool { + if len(s) < 3 || len(s) > 10 { + return false + } + shortUrlRegex := `^[a-zA-Z0-9]+$` + matched, err := regexp.MatchString(shortUrlRegex, s) + if err != nil || !matched { + return false + } + + return true +} diff --git a/web/index.html b/web/index.html index 5ad5df5..2155e7c 100644 --- a/web/index.html +++ b/web/index.html @@ -3,75 +3,353 @@ - Ferurl - URL Shortener + Ferurl - Modern URL Shortener + -

Ferurl - URL Shortener

+
+ -
-
- - - -
+
+
+
+ + +
+
+ +
+
+
+
-
-

Your shortened URL:

+
+
+
Your shortened URL is ready!
+
+ + +
+
+
+
100%
+
Shorter
+
+
+
30
+
Days valid
+
+
+
+
+ +
@@ -80,9 +358,19 @@ e.preventDefault(); const longUrl = document.getElementById('longUrl').value; + const submitBtn = document.querySelector('button[type="submit"]'); + const submitText = submitBtn.querySelector('span:not(.loader)'); + const loader = document.getElementById('submitLoader'); + const errorMessage = document.getElementById('errorMessage'); + + errorMessage.style.display = 'none'; + + submitText.style.display = 'none'; + loader.style.display = 'inline-block'; + submitBtn.disabled = true; try { - const response = await fetch('http://localhost:8080/create', { + const response = await fetch('/create', { method: 'POST', headers: { 'Content-Type': 'application/json', @@ -96,19 +384,44 @@ const data = await response.json(); - // Show the result const resultDiv = document.getElementById('result'); const shortUrlLink = document.getElementById('shortUrl'); - shortUrlLink.href = `http://localhost:8080/${data.shortCode}`; - shortUrlLink.textContent = `http://localhost:8080/${data.shortCode}`; + shortUrlLink.href = data.short_url; + shortUrlLink.textContent = data.short_url; + resultDiv.style.display = 'block'; + setTimeout(() => { + resultDiv.classList.add('visible'); + }, 10); + + document.getElementById('longUrl').value = ''; } catch (error) { console.error('Error:', error); - alert('Failed to shorten URL. Please try again.'); + errorMessage.textContent = 'Failed to shorten URL. Please try again.'; + errorMessage.style.display = 'block'; + } finally { + submitText.style.display = 'inline'; + loader.style.display = 'none'; + submitBtn.disabled = false; } }); + + document.getElementById('copyBtn').addEventListener('click', function() { + const shortUrl = document.getElementById('shortUrl').href; + const copyBtn = this; + + navigator.clipboard.writeText(shortUrl).then(function() { + copyBtn.textContent = 'Copied!'; + copyBtn.classList.add('copied'); + + setTimeout(() => { + copyBtn.textContent = 'Copy'; + copyBtn.classList.remove('copied'); + }, 2000); + }); + });