-
Notifications
You must be signed in to change notification settings - Fork 0
/
shortner.go
160 lines (130 loc) · 3.08 KB
/
shortner.go
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
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
package main
import (
"encoding/json"
"log"
"net/http"
"os"
"sync"
"time"
"github.com/gin-gonic/gin"
)
type URLData struct {
URL string
Count int
}
type URLStore struct {
urls map[string]*URLData
mux sync.RWMutex
}
var store = &URLStore{
urls: make(map[string]*URLData),
}
func (s *URLStore) Set(alias string, data *URLData) {
s.mux.Lock()
defer s.mux.Unlock()
s.urls[alias] = data
}
func (s *URLStore) Get(alias string) (*URLData, bool) {
s.mux.RLock()
defer s.mux.RUnlock()
urlData, exists := s.urls[alias]
return urlData, exists
}
func (s *URLStore) Increment(alias string) {
s.mux.Lock()
defer s.mux.Unlock()
s.urls[alias].Count++
}
func createAlias(c *gin.Context) {
var aliasRequest struct {
URL string `json:"url" binding:"required"`
}
if err := c.ShouldBindJSON(&aliasRequest); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
alias := c.Param("alias")
store.Set(alias, &URLData{URL: aliasRequest.URL})
c.JSON(http.StatusOK, gin.H{"alias": alias})
}
func getAlias(c *gin.Context) {
alias := c.Param("alias")
urlData, exists := store.Get(alias)
if !exists {
c.JSON(http.StatusNotFound, gin.H{"error": "Alias not found"})
return
}
store.Increment(alias)
c.Redirect(http.StatusMovedPermanently, urlData.URL)
}
func saveToDisk() {
store.mux.RLock()
defer store.mux.RUnlock()
jsonData, err := json.Marshal(store.urls)
if err != nil {
log.Fatalf("Failed to marshal store.urls: %v", err)
}
if err := os.WriteFile("store.json", jsonData, 0644); err != nil {
log.Fatalf("Failed to write to file: %v", err)
}
}
func loadFromDisk() {
filename := "store.json"
// Check if the file exists
if _, err := os.Stat(filename); os.IsNotExist(err) {
// Create the file if it doesn't exist
file, err := os.Create(filename)
if err != nil {
log.Fatalf("Failed to create file: %v", err)
}
defer func(file *os.File) {
err := file.Close()
if err != nil {
println("Unable to close file")
return
}
}(file)
emptyJSON := []byte("{}")
if err := os.WriteFile(filename, emptyJSON, 0644); err != nil {
log.Fatalf("Failed to write empty JSON to file: %v", err)
}
}
jsonData, err := os.ReadFile(filename)
if err != nil {
log.Fatalf("Failed to read file: %v", err)
}
var urls map[string]*URLData
if err := json.Unmarshal(jsonData, &urls); err != nil {
log.Fatalf("Failed to unmarshal JSON data: %v", err)
}
store.urls = urls
}
func listStats(c *gin.Context) {
store.mux.RLock()
defer store.mux.RUnlock()
c.JSON(http.StatusOK, store.urls)
}
func main() {
loadFromDisk()
r := gin.New()
r.POST("/:alias", createAlias)
r.GET("/:alias", getAlias)
r.GET("/stats", listStats)
r.StaticFile("stats.html", "./assets/stats.html")
r.GET("/", func(c *gin.Context) {
index := "<html><body>Nothing to see here!</body></html>"
c.Writer.WriteHeader(http.StatusOK)
_, err := c.Writer.Write([]byte(index))
if err != nil {
println("Unable to write response")
return
}
})
ticker := time.NewTicker(10 * time.Second)
go func() {
for range ticker.C {
saveToDisk()
}
}()
log.Fatal(r.Run(":3030"))
}