Example #1
0
// RedirectKey return a http.Handler that redirects to the URL in the store
func RedirectKey(store storage.Database) func(http.ResponseWriter, *http.Request) {
	return func(w http.ResponseWriter, r *http.Request) {
		key := bone.GetValue(r, "key")

		status, err := store.Get(key)
		if err != nil {
			http.Error(w, err.Error(), http.StatusNotFound)
		} else {
			store.Incr(key)
			http.Redirect(w, r, html.EscapeString(status.URL), 301)
		}
	}
}
Example #2
0
// CreateKey return a http.Handler that write a new key to storage
func CreateKey(store storage.Database) func(http.ResponseWriter, *http.Request) {
	return func(w http.ResponseWriter, r *http.Request) {
		r.ParseForm()

		status, err := store.Set(html.EscapeString(r.FormValue("url")))
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}

		json, err := json.Marshal(status)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}

		w.Header().Set("Content-Type", "application/json")
		w.Write(json)
	}
}