main.go 770 B

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. package main
  2. import (
  3. "fmt"
  4. "net/http"
  5. )
  6. const AddForm = `
  7. <form method="POST" action="/add">
  8. URL: <input type="text" name="url">
  9. <input type="submit" value="Add">
  10. </form>
  11. `
  12. var store = NewURLStore()
  13. func main() {
  14. http.HandleFunc("/", Redirect)
  15. http.HandleFunc("/add", Add)
  16. http.ListenAndServe(":8080", nil)
  17. }
  18. func Redirect(w http.ResponseWriter, r *http.Request) {
  19. key := r.URL.Path[1:]
  20. url := store.Get(key)
  21. if url == "" {
  22. http.NotFound(w, r)
  23. return
  24. }
  25. http.Redirect(w, r, url, http.StatusFound)
  26. }
  27. func Add(w http.ResponseWriter, r *http.Request) {
  28. url := r.FormValue("url")
  29. if url == "" {
  30. w.Header().Set("Content-Type", "text/html")
  31. fmt.Fprint(w, AddForm)
  32. return
  33. }
  34. key := store.Put(url)
  35. fmt.Fprintf(w, "http://localhost:8080/%s", key)
  36. }