-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
113 lines (82 loc) · 2.01 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
package main
import (
"crypto/md5"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"log"
"net/http"
"time"
)
type URL struct {
ID string `json:"id"`
OriginalURL string `json:"original_url"`
ShortUrl string `json:"short_url"`
CreatedAt time.Time `json:"created_at"`
}
var urlDB = make(map[string]URL)
func GenerateShortUrl(OriginalURL string) string {
hasher := md5.New()
hasher.Write([]byte(OriginalURL))
data := hasher.Sum(nil)
hash := hex.EncodeToString(data)
return hash[:9]
}
func CreateAndSave(originalUrl string) string {
ShortUrl := GenerateShortUrl(originalUrl)
id := ShortUrl
newData := URL{
ID: id,
OriginalURL: originalUrl,
ShortUrl: ShortUrl,
CreatedAt: time.Now(),
}
urlDB[ShortUrl] = newData
return ShortUrl
}
func GetURL(id string) (URL, error) {
url, err := urlDB[id]
if !err {
return URL{}, errors.New("URL NOT FOUND")
}
return url, nil
}
func ShortenURLController(w http.ResponseWriter, r *http.Request) {
var data struct {
Url string `json:"url"`
}
err := json.NewDecoder(r.Body).Decode(&data)
if err != nil {
http.Error(w, "Invalid Request Body", http.StatusBadRequest)
return
}
shortURL := CreateAndSave(data.Url)
response := struct {
ShrtUrl string `json:"shrtUrl"`
}{ShrtUrl: shortURL}
w.Header().Set("Content-type", "application/json")
json.NewEncoder(w).Encode(response)
fmt.Println(shortURL)
}
func RedirectToMainURLController(w http.ResponseWriter, r *http.Request) {
id := r.URL.Path[len("/redirect/"):]
url, err := GetURL(id)
if err != nil {
http.Error(w, "Invalid request", http.StatusBadRequest)
return
}
fmt.Println(id, url.OriginalURL)
http.Redirect(w, r, url.OriginalURL, http.StatusFound)
}
func main() {
fmt.Println("Setting Up Project.")
http.HandleFunc("/shorten", ShortenURLController)
http.HandleFunc("/redirect/", RedirectToMainURLController)
fmt.Println("Starting the server on PORT 3000")
err := http.ListenAndServe(":3000", nil)
if err != nil {
log.Fatal(err)
return
}
}