-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathhandlers.go
58 lines (47 loc) · 1.24 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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package main
import (
"fmt"
"html/template"
"math/rand"
"net/http"
"time"
)
func handleShorten(w http.ResponseWriter, r *http.Request) {
longURL := r.FormValue("url")
shortURL, slug := generateShortURL(r)
saveURL(slug, longURL)
renderTemplate(w, "index.html", map[string]string{
"ShortURL": shortURL,
"LongURL": longURL,
})
}
func renderTemplate(w http.ResponseWriter, tmpl string, data interface{}) {
tmplPath := fmt.Sprintf("templates/%s", tmpl)
// Parse HTML
t, err := template.ParseFiles(tmplPath)
if err != nil {
http.Error(w, "Error Parsing HTML", http.StatusInternalServerError)
return
}
// Render HTML
err = t.Execute(w, data)
if err != nil {
http.Error(w, "Error Rendering Template", http.StatusInternalServerError)
return
}
}
func generateShortURL(r *http.Request) (string, string) {
rand.NewSource(time.Now().UnixNano())
domain := r.Host
randomString := generateRandomString(6)
shortURL := fmt.Sprintf("http://%s/%s", domain, randomString)
return shortURL, randomString
}
func generateRandomString(length int) string {
const charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
b := make([]byte, length)
for i := range b {
b[i] = charset[rand.Intn(len(charset))]
}
return string(b)
}