api.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  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. */
  22. package api
  23. import (
  24. "net/http"
  25. "github.com/gorilla/mux"
  26. )
  27. // Short is the type of responses provided by the Web API from a target.
  28. type Short struct {
  29. Short string `json:"short"`
  30. }
  31. // Target is the type of requests accepted by the Web API for target submissions.
  32. type Target struct {
  33. Target string `json:"target"`
  34. }
  35. func ListenAndServe(addr string) error {
  36. router := mux.NewRouter()
  37. router.HandleFunc("/{short}", handleGetShort).
  38. Methods("GET", "HEAD").
  39. Name("kurz.get_short")
  40. router.HandleFunc("/", handlePostTarget).
  41. HeadersRegexp("Content-Type", "^application/json$").
  42. Methods("POST").
  43. Name("kurd.post_target")
  44. http.Handle("/", router)
  45. err := http.ListenAndServe(addr, router)
  46. return err
  47. }