//ShortenHandler generates a HTTP handler for a shortening URLs given a datastore backend. func ShortenHandler(db database.ShortenBackend) func(http.ResponseWriter, *http.Request) { return func(w http.ResponseWriter, r *http.Request) { if err := r.ParseForm(); err != nil { returnJSON(nil, &httpError{fmt.Sprintf("couldn't parse form: %s", err.Error()), 500}, w) return } slug := r.PostForm.Get("slug") longURL := r.PostForm.Get("long_url") owner := r.PostForm.Get("owner") for _, res := range reserved { if slug == res { returnJSON(nil, &httpError{fmt.Sprintf("That slug is reserved: %s", slug), 400}, w) return } } if len(slug) == 0 { returnJSON(nil, &httpError{"must provide a slug", 400}, w) return } if len(longURL) == 0 { returnJSON(nil, &httpError{"must provide a destination URL", 400}, w) return } // for now set expiry to never var t time.Time err := db.ShortenURL(slug, longURL, owner, t) var hErr *httpError = nil if err != nil { hErr = &httpError{err.Error(), 500} } returnJSON(nil, hErr, w) return } }