Small changes

This commit is contained in:
ferdzo
2025-08-06 21:27:34 +02:00
parent 3acc9e9ebb
commit af8d26351d
6 changed files with 625 additions and 79 deletions

View File

@@ -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 {

View File

@@ -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),
);

View File

@@ -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
}
return "", fmt.Errorf("URL not found")
}()
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
}
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
}

21
main.go
View File

@@ -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)
}

View File

@@ -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
}

View File

@@ -3,75 +3,353 @@
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Ferurl - URL Shortener</title>
<title>Ferurl - Modern URL Shortener</title>
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap">
<style>
:root {
--primary-color: #3b82f6;
--primary-hover: #2563eb;
--secondary-color: #f3f4f6;
--text-color: #1f2937;
--light-text: #6b7280;
--success-color: #10b981;
--error-color: #ef4444;
--border-radius: 8px;
--box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05);
}
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
body {
font-family: Arial, sans-serif;
max-width: 600px;
margin: 0 auto;
padding: 20px;
font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
background-color: #f9fafb;
color: var(--text-color);
line-height: 1.6;
}
.container {
border: 1px solid #ddd;
border-radius: 5px;
min-height: 100vh;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
padding: 20px;
margin-top: 20px;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
h1 {
color: #333;
.app-container {
width: 100%;
max-width: 550px;
}
.logo {
text-align: center;
margin-bottom: 2rem;
}
.logo h1 {
font-size: 2.5rem;
font-weight: 700;
color: var(--primary-color);
letter-spacing: -0.5px;
}
.logo span {
color: var(--light-text);
font-size: 1rem;
font-weight: 400;
}
.card {
background-color: white;
border-radius: var(--border-radius);
box-shadow: var(--box-shadow);
padding: 2rem;
margin-bottom: 1.5rem;
transition: transform 0.2s ease;
}
.card:hover {
transform: translateY(-5px);
}
form {
display: flex;
flex-direction: column;
gap: 1.5rem;
}
.input-group {
display: flex;
flex-direction: column;
gap: 0.5rem;
}
label {
margin-bottom: 5px;
font-weight: bold;
font-weight: 500;
font-size: 0.875rem;
color: var(--light-text);
}
input[type="url"] {
padding: 8px;
margin-bottom: 15px;
border: 1px solid #ddd;
border-radius: 4px;
font-size: 16px;
width: 100%;
padding: 0.75rem 1rem;
border: 1px solid #e5e7eb;
border-radius: var(--border-radius);
font-size: 1rem;
transition: border-color 0.15s ease;
outline: none;
}
input[type="url"]:focus {
border-color: var(--primary-color);
box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.25);
}
input[type="url"]::placeholder {
color: #d1d5db;
}
button {
background-color: #4CAF50;
padding: 0.75rem 1.5rem;
background-color: var(--primary-color);
color: white;
padding: 10px 15px;
border: none;
border-radius: 4px;
border-radius: var(--border-radius);
font-weight: 500;
font-size: 1rem;
cursor: pointer;
font-size: 16px;
transition: background-color 0.2s ease, transform 0.1s ease;
}
button:hover {
background-color: #45a049;
background-color: var(--primary-hover);
}
.result {
margin-top: 20px;
padding: 15px;
border: 1px solid #ddd;
border-radius: 4px;
background-color: #f9f9f9;
button:active {
transform: scale(0.98);
}
.btn-container {
display: flex;
align-items: center;
gap: 1rem;
}
.loader {
display: none;
width: 24px;
height: 24px;
border: 3px solid rgba(255, 255, 255, 0.3);
border-radius: 50%;
border-top-color: white;
animation: spin 1s ease-in-out infinite;
}
@keyframes spin {
to { transform: rotate(360deg); }
}
.result {
display: none;
opacity: 0;
transition: opacity 0.3s ease;
}
.result.visible {
opacity: 1;
animation: slideIn 0.5s ease forwards;
}
@keyframes slideIn {
from {
transform: translateY(20px);
opacity: 0;
}
to {
transform: translateY(0);
opacity: 1;
}
}
.result-card {
background-color: white;
border-radius: var(--border-radius);
box-shadow: var(--box-shadow);
padding: 1.5rem;
}
.result-title {
font-size: 1rem;
color: var(--light-text);
margin-bottom: 0.75rem;
}
.url-container {
display: flex;
align-items: center;
justify-content: space-between;
background-color: var(--secondary-color);
border-radius: var(--border-radius);
padding: 0.75rem 1rem;
margin-bottom: 1rem;
overflow: hidden;
}
.short-url {
font-weight: 500;
color: var(--primary-color);
text-decoration: none;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
max-width: 80%;
}
.short-url:hover {
text-decoration: underline;
}
.copy-btn {
background-color: transparent;
color: var(--primary-color);
border: 1px solid var(--primary-color);
padding: 0.375rem 0.75rem;
font-size: 0.875rem;
transition: all 0.2s ease;
}
.copy-btn:hover {
background-color: var(--primary-color);
color: white;
}
.copy-btn.copied {
background-color: var(--success-color);
border-color: var(--success-color);
color: white;
}
.stats {
display: flex;
justify-content: space-between;
gap: 1rem;
}
.stat-item {
flex: 1;
text-align: center;
padding: 0.75rem;
background-color: var(--secondary-color);
border-radius: var(--border-radius);
}
.stat-value {
font-size: 1.25rem;
font-weight: 600;
color: var(--primary-color);
}
.stat-label {
font-size: 0.75rem;
color: var(--light-text);
}
.footer {
margin-top: 2rem;
text-align: center;
font-size: 0.875rem;
color: var(--light-text);
}
.footer a {
color: var(--primary-color);
text-decoration: none;
}
.footer a:hover {
text-decoration: underline;
}
/* Error state */
.error-message {
display: none;
color: var(--error-color);
font-size: 0.875rem;
margin-top: 0.5rem;
padding: 0.5rem;
border-radius: var(--border-radius);
background-color: rgba(239, 68, 68, 0.1);
}
@media (max-width: 600px) {
.app-container {
padding: 1rem;
}
.card {
padding: 1.5rem;
}
.stats {
flex-direction: column;
gap: 0.5rem;
}
}
</style>
</head>
<body>
<h1>Ferurl - URL Shortener</h1>
<div class="app-container">
<div class="logo">
<h1>ferurl</h1>
<span>Fast, simple URL shortening</span>
</div>
<div class="container">
<div class="card">
<form id="urlForm">
<label for="longUrl">Enter your long URL:</label>
<input type="url" id="longUrl" name="longUrl" required placeholder="https://example.com/your/very/long/url/goes/here">
<button type="submit">Shorten URL</button>
<div class="input-group">
<label for="longUrl">Enter your long URL</label>
<input
type="url"
id="longUrl"
name="longUrl"
required
placeholder="https://example.com/your/very/long/url/goes/here"
autocomplete="off"
>
</div>
<div class="btn-container">
<button type="submit">
<span>Shorten URL</span>
<span class="loader" id="submitLoader"></span>
</button>
</div>
<div class="error-message" id="errorMessage"></div>
</form>
</div>
<div id="result" class="result">
<p>Your shortened URL: <a id="shortUrl" href="#" target="_blank"></a></p>
<div class="result" id="result">
<div class="result-card">
<div class="result-title">Your shortened URL is ready!</div>
<div class="url-container">
<a id="shortUrl" class="short-url" href="#" target="_blank"></a>
<button id="copyBtn" class="copy-btn">Copy</button>
</div>
<div class="stats">
<div class="stat-item">
<div class="stat-value">100%</div>
<div class="stat-label">Shorter</div>
</div>
<div class="stat-item">
<div class="stat-value">30</div>
<div class="stat-label">Days valid</div>
</div>
</div>
</div>
</div>
<div class="footer">
<p>Made with ❤️ by <a href="https://github.com/ferdzo" target="_blank">ferdzo</a></p>
</div>
</div>
@@ -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);
});
});
</script>
</body>
</html>