url shortener

Jakub Kowalski 1 year ago
commit 0c2b2e935165d67bdb9971f6bc28439ba4059a00
2 changed files with 43 additions and 0 deletions
+3-0go.mod ADDED
View File
@@ -0,0 +1,3 @@
1+module jkowalski/shortener
2+
3+go 1.22
+40-0main.go ADDED
View File
@@ -0,0 +1,40 @@
1+package main
2+
3+import (
4+ "crypto/rand"
5+ "encoding/base64"
6+ "net/http"
7+ "sync"
8+)
9+
10+var (
11+ mu sync.Mutex
12+ urls = map[string]string{}
13+)
14+
15+func code() string {
16+ b := make([]byte, 5)
17+ rand.Read(b)
18+ return base64.RawURLEncoding.EncodeToString(b)
19+}
20+
21+func main() {
22+ http.HandleFunc("POST /shorten", func(w http.ResponseWriter, r *http.Request) {
23+ c := code()
24+ mu.Lock()
25+ urls[c] = r.FormValue("url")
26+ mu.Unlock()
27+ w.Write([]byte(c + "\n"))
28+ })
29+ http.HandleFunc("GET /{code}", func(w http.ResponseWriter, r *http.Request) {
30+ mu.Lock()
31+ u, ok := urls[r.PathValue("code")]
32+ mu.Unlock()
33+ if !ok {
34+ http.NotFound(w, r)
35+ return
36+ }
37+ http.Redirect(w, r, u, http.StatusFound)
38+ })
39+ http.ListenAndServe(":8080", nil)
40+}