api.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. /*
  2. The Kurz Web API exposes HTTP routes for JSON clients, route names to access them, and types for the requests and responses.
  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 SetupRoutes(listenAddress), 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. "github.com/gorilla/mux"
  28. "net/url"
  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. // Route names.
  39. const (
  40. RouteGetShort = "kurz.api.get_short"
  41. RoutePostTarget = "kurz.api.post_target"
  42. )
  43. // Content types.
  44. const (
  45. // JsonType is the MIME JSON type.
  46. JsonType = "application/json"
  47. JsonTypeHeader = JsonType + "; charset=utf-8"
  48. // JsonTypeRegex is a regex matching the MIME JSON type anywhere
  49. JsonTypeRegex = JsonType
  50. )
  51. // SetupRoutes() configures Web API routes on the passed mux.Router.
  52. func SetupRoutes(router *mux.Router) {
  53. // BUG(fgm): improve Accept header matchers once https://github.com/golang/go/issues/19307 is completed.
  54. router.HandleFunc("/{short}", handleGetShort).
  55. HeadersRegexp("Accept", JsonTypeRegex).
  56. Methods("GET", "HEAD").
  57. Name(RouteGetShort)
  58. router.HandleFunc("/", handlePostTarget).
  59. HeadersRegexp("Accept", JsonTypeRegex).
  60. Headers("Content-Type", JsonType).
  61. Methods("POST").
  62. Name(RoutePostTarget)
  63. }
  64. func URLFromRoute(name string, args map[string]string) url.URL {
  65. return url.URL{}
  66. }