-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathaddURLHandler.go
52 lines (43 loc) · 1018 Bytes
/
addURLHandler.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
package main
import (
"net/http"
"sync"
"github.com/gin-gonic/gin"
)
type POSTData struct {
LongURL string `json:"URL"`
}
type POSTresponse struct {
Status string `json:"status"`
ShortName string `json:"short"`
}
func AddURLHandler(c *gin.Context) {
var requestBody POSTData
c.ShouldBindJSON(&requestBody)
var shortName string
if db.URLExist(requestBody.LongURL) {
shortName = db.GetShortName(requestBody.LongURL)
} else {
shortName = GenerateShortName(requestBody.LongURL)
storeIntoDBRedis(requestBody.LongURL, shortName)
}
c.JSON(http.StatusOK, POSTresponse{
Status: "Exist",
ShortName: shortName,
})
}
func storeIntoDBRedis(LongURL, shortName string) {
var wg sync.WaitGroup
wg.Add(2)
// add in database
go func(LongURL string, shortName string) {
defer wg.Done()
db.AddURLPair(LongURL, shortName)
}(LongURL, shortName)
// add in redis
go func(LongURL string, shortName string) {
defer wg.Done()
RedisAdd(LongURL, shortName)
}(LongURL, shortName)
wg.Wait()
}