Add lesson 8: Project: a URL shortener

Daniel Tanaka 11 months ago
parent 11562b3d58 commit 0a727114eaec25d296900e9e0e578b801f781001
3 changed files with 66 additions and 0 deletions
+19-0lessons/08-project-a-url-shortener/README.md ADDED
@@ -0,0 +1,19 @@
1+# Lesson 8: Project: a URL shortener
2+
3+In this lesson you'll work through project: a URL shortener step by step, with short exercises after each idea.
4+
5+Full lesson: [https://glibcode.net/courses/go-apis/lessons/8](https://glibcode.net/courses/go-apis/lessons/8)
6+
7+## Files
8+
9+- `main.go`: the course project: a URL shortener
10+
11+## Run it
12+
13+```sh
14+go run ./lessons/08-project-a-url-shortener
15+```
16+
17+## Exercises
18+
19+See [exercises.md](exercises.md). Ask in the forum once you've tried.
+5-0lessons/08-project-a-url-shortener/exercises.md ADDED
@@ -0,0 +1,5 @@
1+# Exercises: lesson 8
2+
3+1. Time yourself: rewrite the example from memory in 10 minutes, then diff it against the original.
4+2. Rewrite the main part so it runs twice with two different inputs, without copying the code.
5+3. Find one thing in `main.go` you could name better and rename it everywhere.
+42-0lessons/08-project-a-url-shortener/main.go ADDED
@@ -0,0 +1,42 @@
1+package main
2+
3+import (
4+ "crypto/rand"
5+ "encoding/base64"
6+ "net/http"
7+ "sync"
8+)
9+
10+type store struct {
11+ mu sync.RWMutex
12+ urls map[string]string
13+}
14+
15+func (s *store) add(url string) string {
16+ b := make([]byte, 6)
17+ rand.Read(b)
18+ code := base64.RawURLEncoding.EncodeToString(b)
19+ s.mu.Lock()
20+ s.urls[code] = url
21+ s.mu.Unlock()
22+ return code
23+}
24+
25+func main() {
26+ s := &store{urls: map[string]string{}}
27+ http.HandleFunc("POST /shorten", func(w http.ResponseWriter, r *http.Request) {
28+ code := s.add(r.FormValue("url"))
29+ w.Write([]byte("/" + code + "\n"))
30+ })
31+ http.HandleFunc("GET /{code}", func(w http.ResponseWriter, r *http.Request) {
32+ s.mu.RLock()
33+ url, ok := s.urls[r.PathValue("code")]
34+ s.mu.RUnlock()
35+ if !ok {
36+ http.NotFound(w, r)
37+ return
38+ }
39+ http.Redirect(w, r, url, http.StatusFound)
40+ })
41+ http.ListenAndServe(":8080", nil)
42+}