Beispiel #1
0
// ListHandler generates a HTTP handler for listing URL's given a datastore backend.
func ListHandler(db database.ShortenBackend) func(http.ResponseWriter, *http.Request) {
	return func(w http.ResponseWriter, r *http.Request) {
		var hErr *httpError = nil
		sObj, err := db.GetList()
		if err != nil {
			hErr = &httpError{err.Error(), 500}
		}

		returnJSON(sObj, hErr, w)
	}
}
Beispiel #2
0
// DeleteHandler generates a HTTP handler for deleting URL's given a datastore backend.
func DeleteHandler(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")
		var hErr *httpError = nil
		err := db.DeleteURL(slug)
		if err != nil {
			hErr = &httpError{err.Error(), 500}
		}
		returnJSON(nil, hErr, w)
	}
}
Beispiel #3
0
// RedirectHandler redirects users to their desired location.
// Not accessed via Ajax, just by end users
func RedirectHandler(db database.ShortenBackend, domain string) func(http.ResponseWriter, *http.Request) {
	return func(w http.ResponseWriter, r *http.Request) {
		slug := mux.Vars(r)["slug"]
		long, err := db.GetLongURL(slug)
		var errNotFound database.ErrNotFound
		if err == errNotFound {
			w.WriteHeader(404)
			fmt.Fprintf(w, fmt.Sprintf(errMsgTemplate, slug, domain, domain))
			return
		}
		if err != nil {
			log.Println(kayvee.FormatLog("shorty", kayvee.Error, "redirect", msg{
				"err": err.Error(),
			}))
			w.WriteHeader(500)
			w.Write([]byte(err.Error()))
			return
		}
		http.Redirect(w, r, long, 302)
		return
	}
}
Beispiel #4
0
//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
	}
}