main.go 724 B

1234567891011121314151617181920212223242526272829303132333435363738394041
  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. fmt.Fprint(w, AddForm)
  31. return
  32. }
  33. key := store.Put(url)
  34. fmt.Fprintf(w, "http://localhost:8080/%s", key)
  35. }