44 lines886 B

package main
import (
"crypto/rand"
"encoding/base64"
"net/http"
"sync"
)
type store struct {
mu sync.RWMutex
urls map[string]string
}
func (s *store) add(url string) string {
b := make([]byte, 6)
rand.Read(b)
code := base64.RawURLEncoding.EncodeToString(b)
s.mu.Lock()
s.urls[code] = url
s.mu.Unlock()
return code
}
func main() {
s := &store{urls: map[string]string{}}
http.HandleFunc("POST /shorten", func(w http.ResponseWriter, r *http.Request) {
code := s.add(r.FormValue("url"))
w.Write([]byte("/" + code + "\n"))
})
http.HandleFunc("GET /{code}", func(w http.ResponseWriter, r *http.Request) {
s.mu.RLock()
url, ok := s.urls[r.PathValue("code")]
s.mu.RUnlock()
if !ok {
http.NotFound(w, r)
return
}
http.Redirect(w, r, url, http.StatusFound)
})
http.ListenAndServe(":8080", nil)
}
// Try changing the values above and run it again.