main.go 781 B

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