-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
96 lines (73 loc) · 1.7 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
package main
import (
"fmt"
"log"
"net/http"
"sync"
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
"github.com/lithammer/shortuuid/v4"
)
type Mapper struct {
Mapping map[string]string
Lock sync.Mutex
}
var urlMapper Mapper
func init() {
// intialise mapper
urlMapper = Mapper{
Mapping: make(map[string]string),
}
}
func main() {
r := chi.NewRouter()
r.Use(middleware.Logger)
r.Get("/", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("server is running..."))
})
r.Post("/short-it", createShortUrlHandler)
r.Get("/short/{key}", redirectHandler)
http.ListenAndServe(":3000", r)
}
func createShortUrlHandler(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
u := r.Form.Get("URL")
if u == "" {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte("URL cannot be empty"))
return
}
// generate key
key := shortuuid.New()
// insert
insertMapping(key, u)
log.Printf("shortened URL: %s\n", key)
w.WriteHeader(http.StatusOK)
w.Write([]byte(fmt.Sprintf("http://localhost:3000/short/%s", key)))
}
func insertMapping(key string, u string) {
urlMapper.Lock.Lock()
defer urlMapper.Lock.Unlock()
urlMapper.Mapping[key] = u
}
func redirectHandler(w http.ResponseWriter, r *http.Request) {
key := chi.URLParam(r, "key")
if key == "" {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte("key cannot be empty"))
return
}
// fetch mapping
u := fetchMapping(key)
if u == "" {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte("url cannot be empty"))
return
}
http.Redirect(w, r, u, http.StatusFound)
}
func fetchMapping(key string) string {
urlMapper.Lock.Lock()
defer urlMapper.Lock.Unlock()
return urlMapper.Mapping[key]
}