main.go 992 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. package main
  2. import (
  3. "flag"
  4. "fmt"
  5. "net/http"
  6. )
  7. var (
  8. listenAddr = flag.String("http", ":8080", "http listen address")
  9. dataFile = flag.String("file", "store.json", "data store file name")
  10. hostname = flag.String("host", "localhost:8080", "http host name")
  11. )
  12. var store *URLStore
  13. func main() {
  14. flag.Parse()
  15. store = NewURLStore(*dataFile)
  16. http.HandleFunc("/", Redirect)
  17. http.HandleFunc("/add", Add)
  18. http.ListenAndServe(*listenAddr, nil)
  19. }
  20. func Redirect(w http.ResponseWriter, r *http.Request) {
  21. key := r.URL.Path[1:]
  22. url := store.Get(key)
  23. if url == "" {
  24. http.NotFound(w, r)
  25. return
  26. }
  27. http.Redirect(w, r, url, http.StatusFound)
  28. }
  29. func Add(w http.ResponseWriter, r *http.Request) {
  30. url := r.FormValue("url")
  31. if url == "" {
  32. fmt.Fprint(w, AddForm)
  33. return
  34. }
  35. key := store.Put(url)
  36. fmt.Fprintf(w, "http://%s/%s", *hostname, key)
  37. }
  38. const AddForm = `
  39. <form method="POST" action="/add">
  40. URL: <input type="text" name="url">
  41. <input type="submit" value="Add">
  42. </form>
  43. `