api.go 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  1. package web
  2. import (
  3. "encoding/base64"
  4. "encoding/json"
  5. "errors"
  6. "net/http"
  7. "net/url"
  8. "strconv"
  9. "strings"
  10. "time"
  11. "github.com/kellegous/go/context"
  12. "github.com/syndtr/goleveldb/leveldb"
  13. )
  14. const (
  15. alpha = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
  16. )
  17. var (
  18. errInvalidURL = errors.New("Invalid URL")
  19. errRedirectLoop = errors.New(" I'm sorry, Dave. I'm afraid I can't do that")
  20. genURLPrefix byte = ':'
  21. postGenCursor = []byte{genURLPrefix + 1}
  22. )
  23. // A very simple encoding of numeric ids. This is simply a base62 encoding
  24. // prefixed with ":"
  25. func encodeID(id uint64) string {
  26. n := uint64(len(alpha))
  27. b := make([]byte, 0, 8)
  28. if id == 0 {
  29. return "0"
  30. }
  31. b = append(b, genURLPrefix)
  32. for id > 0 {
  33. b = append(b, alpha[id%n])
  34. id /= n
  35. }
  36. return string(b)
  37. }
  38. // Advance to the next contetxt id and encode it as an ID.
  39. func nextEncodedID(ctx *context.Context) (string, error) {
  40. id, err := ctx.NextID()
  41. if err != nil {
  42. return "", err
  43. }
  44. return encodeID(id), nil
  45. }
  46. // Check that the given URL is suitable as a shortcut link.
  47. func validateURL(r *http.Request, s string) error {
  48. u, err := url.Parse(s)
  49. if err != nil {
  50. return errInvalidURL
  51. }
  52. switch u.Scheme {
  53. case "http", "https", "mailto", "ftp":
  54. break
  55. default:
  56. return errInvalidURL
  57. }
  58. if r.Host == u.Host {
  59. return errRedirectLoop
  60. }
  61. return nil
  62. }
  63. func apiURLPost(ctx *context.Context, w http.ResponseWriter, r *http.Request) {
  64. p := parseName("/api/url/", r.URL.Path)
  65. var req struct {
  66. URL string `json:"url"`
  67. }
  68. if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
  69. writeJSONError(w, "invalid json", http.StatusBadRequest)
  70. return
  71. }
  72. if req.URL == "" {
  73. writeJSONError(w, "url required", http.StatusBadRequest)
  74. return
  75. }
  76. if isBannedName(p) {
  77. writeJSONError(w, "name cannot be used", http.StatusBadRequest)
  78. return
  79. }
  80. if err := validateURL(r, req.URL); err != nil {
  81. writeJSONError(w, err.Error(), http.StatusBadRequest)
  82. return
  83. }
  84. // If no name is specified, an ID must be generate.
  85. if p == "" {
  86. var err error
  87. p, err = nextEncodedID(ctx)
  88. if err != nil {
  89. writeJSONBackendError(w, err)
  90. return
  91. }
  92. }
  93. rt := context.Route{
  94. URL: req.URL,
  95. Time: time.Now(),
  96. }
  97. if err := ctx.Put(p, &rt); err != nil {
  98. writeJSONBackendError(w, err)
  99. return
  100. }
  101. writeJSONRoute(w, p, &rt)
  102. }
  103. func apiURLGet(ctx *context.Context, w http.ResponseWriter, r *http.Request) {
  104. p := parseName("/api/url/", r.URL.Path)
  105. if p == "" {
  106. writeJSONError(w, "no name given", http.StatusBadRequest)
  107. return
  108. }
  109. rt, err := ctx.Get(p)
  110. if err == leveldb.ErrNotFound {
  111. writeJSONError(w, "Not Found", http.StatusNotFound)
  112. return
  113. } else if err != nil {
  114. writeJSONBackendError(w, err)
  115. return
  116. }
  117. writeJSONRoute(w, p, rt)
  118. }
  119. func apiURLDelete(ctx *context.Context, w http.ResponseWriter, r *http.Request) {
  120. p := parseName("/api/url/", r.URL.Path)
  121. if p == "" {
  122. writeJSONError(w, "name required", http.StatusBadRequest)
  123. return
  124. }
  125. if err := ctx.Del(p); err != nil {
  126. writeJSONBackendError(w, err)
  127. return
  128. }
  129. writeJSONOk(w)
  130. }
  131. func parseCursor(v string) ([]byte, error) {
  132. if v == "" {
  133. return nil, nil
  134. }
  135. return base64.URLEncoding.DecodeString(v)
  136. }
  137. func parseInt(v string, def int) (int, error) {
  138. if v == "" {
  139. return def, nil
  140. }
  141. i, err := strconv.ParseInt(v, 10, 64)
  142. if err != nil {
  143. return 0, err
  144. }
  145. return int(i), nil
  146. }
  147. func parseBool(v string, def bool) (bool, error) {
  148. if v == "" {
  149. return def, nil
  150. }
  151. v = strings.ToLower(v)
  152. if v == "true" || v == "t" || v == "1" {
  153. return true, nil
  154. }
  155. if v == "false" || v == "f" || v == "0" {
  156. return false, nil
  157. }
  158. return false, errors.New("invalid boolean value")
  159. }
  160. func apiURLsGet(ctx *context.Context, w http.ResponseWriter, r *http.Request) {
  161. c, err := parseCursor(r.FormValue("cursor"))
  162. if err != nil {
  163. writeJSONError(w, "invalid cursor value", http.StatusBadRequest)
  164. return
  165. }
  166. lim, err := parseInt(r.FormValue("limit"), 100)
  167. if err != nil || lim <= 0 || lim > 10000 {
  168. writeJSONError(w, "invalid limit value", http.StatusBadRequest)
  169. return
  170. }
  171. ig, err := parseBool(r.FormValue("include-generated-names"), false)
  172. if err != nil {
  173. writeJSONError(w, "invalid include-generated-names value", http.StatusBadRequest)
  174. return
  175. }
  176. res := msgRoutes{
  177. Ok: true,
  178. }
  179. iter := ctx.List(c)
  180. defer iter.Release()
  181. for iter.Next() {
  182. // if we should be ignoring generated links, skip over that range.
  183. if !ig && isGenerated(iter.Name()) {
  184. iter.Seek(postGenCursor)
  185. if !iter.Valid() {
  186. break
  187. }
  188. }
  189. res.Routes = append(res.Routes, &routeWithName{
  190. Name: iter.Name(),
  191. Route: iter.Route(),
  192. })
  193. if len(res.Routes) == lim {
  194. break
  195. }
  196. }
  197. if iter.Next() {
  198. res.Next = base64.URLEncoding.EncodeToString([]byte(iter.Name()))
  199. }
  200. if err := iter.Error(); err != nil {
  201. writeJSONBackendError(w, err)
  202. return
  203. }
  204. writeJSON(w, &res, http.StatusOK)
  205. }
  206. func apiURL(ctx *context.Context, w http.ResponseWriter, r *http.Request) {
  207. switch r.Method {
  208. case "POST":
  209. apiURLPost(ctx, w, r)
  210. case "GET":
  211. apiURLGet(ctx, w, r)
  212. case "DELETE":
  213. apiURLDelete(ctx, w, r)
  214. default:
  215. writeJSONError(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusOK) // fix
  216. }
  217. }
  218. func apiURLs(ctx *context.Context, w http.ResponseWriter, r *http.Request) {
  219. switch r.Method {
  220. case "GET":
  221. apiURLsGet(ctx, w, r)
  222. default:
  223. writeJSONError(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusOK) // fix
  224. }
  225. }
  226. // Setup ...
  227. func Setup(m *http.ServeMux, ctx *context.Context) {
  228. m.HandleFunc("/api/url/", func(w http.ResponseWriter, r *http.Request) {
  229. apiURL(ctx, w, r)
  230. })
  231. m.HandleFunc("/api/urls/", func(w http.ResponseWriter, r *http.Request) {
  232. apiURLs(ctx, w, r)
  233. })
  234. }