-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathhandlers.go
44 lines (36 loc) · 1.3 KB
/
handlers.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
package main
import (
"encoding/json"
"net/http"
)
// ShortenURLHandler handles requests to shorten URLs
func ShortenURLHandler(store *URLStore) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var reqData map[string]string
if err := json.NewDecoder(r.Body).Decode(&reqData); err != nil {
http.Error(w, "Invalid request payload", http.StatusBadRequest)
return
}
originalURL := reqData["url"]
if originalURL == "" {
http.Error(w, "URL cannot be empty", http.StatusBadRequest)
return
}
shortURL := GenerateShortURL()
store.SaveURL(shortURL, originalURL)
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]string{"short_url": shortURL})
}
}
// RedirectURLHandler handles redirection from short URLs to original URLs
func RedirectURLHandler(store *URLStore) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
shortURL := r.URL.Path[len("/r/"):]
originalURL, exists := store.GetOriginalURL(shortURL)
if !exists {
http.Error(w, "URL not found", http.StatusNotFound)
return
}
http.Redirect(w, r, originalURL, http.StatusFound)
}
}