package main import ( "crypto/rand" "encoding/base64" "net/http" "sync" ) var ( mu sync.Mutex urls = map[string]string{} ) func code() string { b := make([]byte, 5) rand.Read(b) return base64.RawURLEncoding.EncodeToString(b) } func main() { http.HandleFunc("POST /shorten", func(w http.ResponseWriter, r *http.Request) { c := code() mu.Lock() urls[c] = r.FormValue("url") mu.Unlock() w.Write([]byte(c + "\n")) }) http.HandleFunc("GET /{code}", func(w http.ResponseWriter, r *http.Request) { mu.Lock() u, ok := urls[r.PathValue("code")] mu.Unlock() if !ok { http.NotFound(w, r) return } http.Redirect(w, r, u, http.StatusFound) }) http.ListenAndServe(":8080", nil) }