-
Notifications
You must be signed in to change notification settings - Fork 0
/
tiny-url.go
81 lines (65 loc) · 1.72 KB
/
tiny-url.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
package main
import (
"encoding/json"
"fmt"
"net/http"
"strings"
"github.com/arrwhidev/base-converter"
)
const offset = uint64(300)
var db = make(map[uint64]string)
type jsonInterface struct {
URL string `json:"url"`
}
func shorten(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "Expecting POST request", http.StatusBadRequest)
return
}
if r.Header.Get("Content-Type") != "application/json" {
http.Error(w, "Invalid Content-Type", http.StatusUnsupportedMediaType)
return
}
// Decode JSON.
var jsonRequest jsonInterface
decoder := json.NewDecoder(r.Body)
err := decoder.Decode(&jsonRequest)
if err != nil {
http.Error(w, "Invalid JSON", http.StatusUnprocessableEntity)
return
}
// Insert new row into database.
nextID := offset + uint64(len(db)) + 1
db[nextID] = jsonRequest.URL
encoded := radix.Encode(uint64(nextID), radix.Base62)
// Write JSON response object
encoder := json.NewEncoder(w)
encoder.Encode(&jsonInterface{
URL: "http://localhost:8080/" + encoded,
})
}
func expand(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
http.Error(w, "Expecting GET request", http.StatusBadRequest)
return
}
shortCode := strings.Split(r.RequestURI, "/")[1]
id := radix.Decode(shortCode, radix.Base62)
if url, ok := db[id]; ok {
http.Redirect(w, r, url, http.StatusMovedPermanently)
} else {
http.Error(w, "Unecognised short code: "+shortCode, http.StatusNotFound)
}
}
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
if r.RequestURI == "/" {
shorten(w, r)
} else {
expand(w, r)
}
})
fmt.Println("Listening on :8080...")
srv := &http.Server{Addr: ":8080"}
srv.ListenAndServe()
}