api.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. /*
  2. The Kurz Web API exposes these routes:
  3. - GET "/<short>" : resolve a short URL
  4. - Handler: handleGetShort()
  5. - Success: 307 to matching target URL
  6. - Client request incorrect: 400
  7. - Short not yet defined: 404 no matching target
  8. - Target blocked for permission reasons: 403
  9. - Target legally censored: 451
  10. - Server failure: 50*
  11. - POST "/" with <target>: create a short URL from a target URL
  12. - Handler: handlePostTarget()
  13. - Success: 201 with <new short>
  14. - Already existing short: 409 with <existing short>
  15. - Target blocked for permission reasons: 403
  16. - Target legally censored: 451
  17. - Server failure: 50*
  18. Code 451 MAY be replaced by 403, for example when legal censorship includes a
  19. gag order, super-injunction (UK), National security letter (US) or similar
  20. mechanisms.
  21. These routes are exposed by running ListenAndServe(address), which is enough to
  22. configure the Kurz domain API. Be sure to also configure the domain SPI to have
  23. a complete application.
  24. */
  25. package api
  26. import (
  27. "net/http"
  28. "github.com/gorilla/mux"
  29. )
  30. // Short is the type of responses provided by the Web API from a target.
  31. type Short struct {
  32. Short string `json:"short"`
  33. }
  34. // Target is the type of requests accepted by the Web API for target submissions.
  35. type Target struct {
  36. Target string `json:"target"`
  37. }
  38. /*
  39. ListenAndServe() is the
  40. */
  41. func ListenAndServe(addr string) error {
  42. router := mux.NewRouter()
  43. router.HandleFunc("/{short}", handleGetShort).
  44. Methods("GET", "HEAD").
  45. Name("kurz.get_short")
  46. router.HandleFunc("/", handlePostTarget).
  47. HeadersRegexp("Content-Type", "^application/json$").
  48. Methods("POST").
  49. Name("kurd.post_target")
  50. http.Handle("/", router)
  51. err := http.ListenAndServe(addr, router)
  52. return err
  53. }