Repository navigation
Expand file tree
/
Copy pathmain.go
More file actions
89 lines (71 loc) · 1.82 KB
/
Copy pathmain.go
File metadata and controls
89 lines (71 loc) · 1.82 KB
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
package main
import (
"crypto/rand"
"encoding/base64"
"encoding/json"
"fmt"
"log"
"net/http"
"strings"
"sync"
)
type URLStore struct {
URLs map[string]string
mu sync.RWMutex
}
type shortenRequest struct {
URL string `json:"url"`
}
type shortenResponse struct {
ShortURL string `json:"short_url"`
}
func generateShortKey() (string, error) {
b := make([]byte, 6)
_, err := rand.Read(b)
if err != nil {
return "", err
}
return base64.RawURLEncoding.EncodeToString(b), nil
}
func (store *URLStore) shortenURL(w http.ResponseWriter, r *http.Request) {
var req shortenRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, "Invalid request body", http.StatusBadRequest)
return
}
if !strings.HasPrefix(req.URL, "http://") && !strings.HasPrefix(req.URL, "https://") {
http.Error(w, "Invalid URL", http.StatusBadRequest)
return
}
shortKey, err := generateShortKey()
if err != nil {
http.Error(w, "Failed to generate short key", http.StatusInternalServerError)
return
}
store.mu.Lock()
store.URLs[shortKey] = req.URL
store.mu.Unlock()
resp := shortenResponse{ShortURL: fmt.Sprintf("http://localhost:8080/%s", shortKey)}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(resp)
}
func (store *URLStore) redirectURL(w http.ResponseWriter, r *http.Request) {
shortKey := r.URL.Path[1:]
store.mu.RLock()
originalURL, ok := store.URLs[shortKey]
store.mu.RUnlock()
if !ok {
http.Error(w, "URL not found", http.StatusNotFound)
return
}
http.Redirect(w, r, originalURL, http.StatusFound)
}
func main() {
store := URLStore{
URLs: make(map[string]string),
}
http.HandleFunc("/shorten", store.shortenURL)
http.HandleFunc("/", store.redirectURL)
fmt.Println("Server running on http://localhost:8080")
log.Fatal(http.ListenAndServe(":8080", nil))
}