-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
247 lines (209 loc) · 6.26 KB
/
main.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
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
package main
import (
"context"
"database/sql"
"fmt"
"log"
"time"
db "github.com/SemmiDev/fiber-shortener/db/sqlc"
"github.com/SemmiDev/fiber-shortener/util"
"github.com/go-redis/redis/v8"
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/cors"
"github.com/gofiber/fiber/v2/middleware/logger"
"github.com/gofiber/fiber/v2/middleware/recover"
"github.com/golang-migrate/migrate/v4"
_ "github.com/golang-migrate/migrate/v4/database/postgres"
_ "github.com/golang-migrate/migrate/v4/source/file"
_ "github.com/lib/pq"
"github.com/teris-io/shortid"
"golang.org/x/sync/singleflight"
)
type server struct {
config util.Config
store db.Store
app *fiber.App
redisStore *redis.Client
redisQueue *util.RedisQueue
generator *shortid.Shortid
singleflightGroupResolveURL singleflight.Group
}
type request struct {
URL string `json:"url"`
}
func (s *server) shortenURLHandler(c *fiber.Ctx) error {
var req request
if err := c.BodyParser(&req); err != nil {
return fiber.NewError(fiber.StatusBadRequest, "cannot parse body")
}
host := string(c.Context().Host())
v, err, shared := s.singleflightGroupResolveURL.Do(req.URL, func() (interface{}, error) {
shortURL, err := s.redisStore.Get(c.Context(), req.URL).Result()
if err == nil && shortURL != "" {
return fmt.Sprintf("%s/%s", host, shortURL), nil
}
link, err := s.store.CreateLinkTx(c.Context(), db.CreateLinkParams{
LongUrl: req.URL,
ShortUrl: s.generator.MustGenerate(),
})
if err != nil {
return nil, fiber.NewError(fiber.StatusInternalServerError, "cannot create short url")
}
go s.redisQueue.Enqueue(
util.KVRedisQueue{Key: link.LongUrl, Val: link.ShortUrl},
util.KVRedisQueue{Key: link.ShortUrl, Val: link.LongUrl},
)
return fmt.Sprintf("%s/%s", host, link.ShortUrl), nil
})
if shared {
log.Println("shared: ", req.URL)
if err != nil {
return err
} else {
shortURL := v.(string)
return c.JSON(fiber.Map{
"short_url": host + "/" + shortURL,
})
}
}
// check if url already exist in redis
shortURL, err := s.redisStore.Get(c.Context(), req.URL).Result()
if err == nil && shortURL != "" {
return c.JSON(fiber.Map{
"short_url": host + "/" + shortURL,
})
}
link, err := s.store.CreateLinkTx(c.Context(), db.CreateLinkParams{
LongUrl: req.URL,
ShortUrl: s.generator.MustGenerate(),
})
if err != nil {
return fiber.NewError(fiber.StatusInternalServerError, "cannot create short url")
}
go s.redisQueue.Enqueue(
util.KVRedisQueue{Key: link.LongUrl, Val: link.ShortUrl},
util.KVRedisQueue{Key: link.ShortUrl, Val: link.LongUrl},
)
return c.JSON(fiber.Map{
"short_url": host + "/" + link.ShortUrl,
})
}
func (s *server) resolveURLHandler(c *fiber.Ctx) error {
shortURL := c.Params("short_url") // also sharedProcessKey using in singleflightGroupResolveURL
if shortURL == "" {
return fiber.NewError(fiber.StatusBadRequest, "please provide short url")
}
v, err, shared := s.singleflightGroupResolveURL.Do(shortURL, func() (interface{}, error) {
longURL, err := s.redisStore.Get(c.Context(), shortURL).Result()
if err == nil {
return longURL, nil
}
link, err := s.store.GetLinkByShortURL(c.Context(), shortURL)
if err != nil {
if err == sql.ErrNoRows {
return nil, fiber.NewError(fiber.StatusNotFound, "cannot find short url")
}
return nil, fiber.NewError(fiber.StatusInternalServerError, "cannot get short url")
}
go s.redisQueue.Enqueue(
util.KVRedisQueue{Key: link.LongUrl, Val: link.ShortUrl},
util.KVRedisQueue{Key: link.ShortUrl, Val: link.LongUrl},
)
return link, nil
})
if shared {
log.Println("shared: ", shortURL)
if err != nil {
return err
} else {
url := v.(string)
return c.Redirect(url)
}
}
longURL, err := s.redisStore.Get(c.Context(), shortURL).Result()
if err == nil {
return c.Redirect(longURL)
}
link, err := s.store.GetLinkByShortURL(c.Context(), shortURL)
if err != nil {
if err == sql.ErrNoRows {
return fiber.NewError(fiber.StatusNotFound, "cannot find short url")
}
return fiber.NewError(fiber.StatusInternalServerError, "cannot get short url")
}
go s.redisQueue.Enqueue(
util.KVRedisQueue{Key: link.LongUrl, Val: link.ShortUrl},
util.KVRedisQueue{Key: link.ShortUrl, Val: link.LongUrl},
)
return c.Redirect(link.LongUrl)
}
func main() {
// load config from app.env file
config, err := util.LoadConfig(".")
if err != nil {
log.Fatal("cannot load config:", err)
}
// connect to database
conn, err := sql.Open(config.DBDriver, config.DBSource)
if err != nil {
log.Fatal("cannot connect to db:", err)
}
// ping to db
if err := conn.Ping(); err != nil {
log.Fatal("cannot ping db:", err)
}
//set connection pool
conn.SetMaxOpenConns(25)
conn.SetMaxIdleConns(25)
conn.SetConnMaxLifetime(5 * time.Minute)
// run migration
migration, err := migrate.New(config.MigrationURL, config.DBSource)
if err != nil {
log.Fatal("cannot create new migrate instance:", err)
}
if err = migration.Up(); err != nil && err != migrate.ErrNoChange {
log.Fatal("failed to run migrate up:", err)
}
// create new store
store := db.NewStore(conn)
// create redis client and connect to redis
redisClient := redis.NewClient(&redis.Options{
Addr: config.RedisHost,
Password: config.RedisPassword,
DB: 0,
})
err = redisClient.Ping(context.Background()).Err()
if err != nil {
log.Fatal("cannot connect to redis:", err)
}
redisQueue := util.NewRedisQueue(redisClient)
// create generator instance
generator, err := shortid.New(31, shortid.DefaultABC, 2342)
if err != nil {
log.Fatal("cannot create new generator instance:", err)
}
// create new fiber instance
app := fiber.New()
// set middleware
app.Use(logger.New())
app.Use(recover.New())
app.Use(cors.New())
// create new server
s := &server{
app: app,
config: config,
store: store,
redisStore: redisClient,
redisQueue: redisQueue,
generator: generator,
}
s.app.Static("/", "./frontend/src")
// register routes
s.app.Post("/shorten", s.shortenURLHandler)
s.app.Get("/:short_url", s.resolveURLHandler)
// start server
err = s.app.Listen(config.HTTPServerAddress)
if err != nil {
log.Fatal("cannot start http server:", err)
}
}