main.go 735 B

1234567891011121314151617181920212223242526272829303132333435363738394041
  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. fmt.Fprint(w, AddForm)
  25. return
  26. }
  27. key := store.Put(url)
  28. fmt.Fprintf(w, "http://localhost:8080/%s", key)
  29. }
  30. const AddForm = `
  31. <form method="POST" action="/add">
  32. URL: <input type="text" name="url">
  33. <input type="submit" value="Add">
  34. </form>
  35. `