Repository navigation
Expand file tree
/
Copy pathmain.go
More file actions
136 lines (114 loc) · 3.42 KB
/
Copy pathmain.go
File metadata and controls
136 lines (114 loc) · 3.42 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
package main
import (
"net/http"
"net/url"
"os"
"strings"
"time"
"github.com/AhmetTK4/goshort/service"
"github.com/AhmetTK4/goshort/storage"
"github.com/gin-contrib/cors"
"github.com/gin-gonic/gin"
)
func main() {
storage.InitRedis()
defer storage.RDB.Close()
if err := newRouter().Run(":8080"); err != nil {
panic(err)
}
}
func newRouter() *gin.Engine {
baseURL := strings.TrimRight(os.Getenv("BASE_URL"), "/")
if baseURL == "" {
baseURL = "http://localhost:8080"
}
r := gin.Default()
r.Use(cors.New(cors.Config{
AllowOrigins: []string{"http://localhost:3000"},
AllowMethods: []string{"GET", "POST", "OPTIONS"},
AllowHeaders: []string{"Origin", "Content-Type"},
ExposeHeaders: []string{"Content-Length"},
AllowCredentials: true,
MaxAge: 12 * time.Hour,
}))
r.OPTIONS("/*path", func(c *gin.Context) {
c.AbortWithStatus(204)
})
r.POST("/api/shorten", func(c *gin.Context) {
var request struct {
URL string `json:"url" binding:"required"`
CustomCode string `json:"custom_code,omitempty"`
}
if err := c.ShouldBindJSON(&request); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request"})
return
}
shortCodeKey := "original:" + request.URL
parsed, err := url.ParseRequestURI(request.URL)
if err != nil || parsed.Host == "" || (parsed.Scheme != "http" && parsed.Scheme != "https") || parsed.User != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "URL must be an absolute HTTP or HTTPS URL without credentials"})
return
}
existingShortCode, err := storage.RDB.Get(storage.Ctx, shortCodeKey).Result()
if err == nil {
c.JSON(http.StatusOK, gin.H{
"short_url": baseURL + "/g/" + existingShortCode,
})
return
}
var shortCode string
if request.CustomCode != "" {
if !service.ValidateCustomCode(request.CustomCode) {
c.JSON(http.StatusBadRequest, gin.H{"error": "Custom code must be 3-20 alphanumeric characters"})
return
}
exists, err := storage.RDB.Exists(storage.Ctx, request.CustomCode).Result()
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Redis error"})
return
}
if exists > 0 {
c.JSON(http.StatusConflict, gin.H{"error": "Custom code already exists"})
return
}
shortCode = request.CustomCode
} else {
shortCode = service.GenerateShortCode(6)
}
err = storage.RDB.Set(storage.Ctx, shortCode, request.URL, 1*time.Hour).Err()
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Redis error"})
return
}
err = storage.RDB.Set(storage.Ctx, shortCodeKey, shortCode, 1*time.Hour).Err()
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Redis error"})
return
}
c.JSON(http.StatusOK, gin.H{
"short_url": baseURL + "/g/" + shortCode,
})
})
r.GET("/g/:shortCode", func(c *gin.Context) {
shortCode := c.Param("shortCode")
longURL, err := storage.RDB.Get(storage.Ctx, shortCode).Result()
if err != nil {
c.JSON(http.StatusNotFound, gin.H{"error": "Short URL not found"})
return
}
storage.RDB.Incr(storage.Ctx, "clicks:"+shortCode)
c.Redirect(http.StatusFound, longURL)
})
r.GET("/api/stats/:shortCode", func(c *gin.Context) {
shortCode := c.Param("shortCode")
count, err := storage.RDB.Get(storage.Ctx, "clicks:"+shortCode).Result()
if err != nil {
count = "0"
}
c.JSON(http.StatusOK, gin.H{
"short_code": shortCode,
"clicks": count,
})
})
return r
}