Exemple #1
0
func Patch(w http.ResponseWriter, r *http.Request) {
	ctx := appengine.NewContext(r)
	listId, err := strconv.ParseInt(mux.Vars(r)["listId"], 10, 64)
	if err != nil {
		jsonError.NewNotFound("").HttpError(w)
		return
	}

	body, err := ioutil.ReadAll(r.Body)
	if err != nil {
		jsonError.NewBadRequest("").HttpError(w)
		return
	}

	obj, err := jsonpatch.DecodePatch(body)
	if err != nil {
		jsonError.NewBadRequest("").HttpError(w)
		return
	}

	var list model.List
	key := datastore.NewKey(ctx, "List", "", listId, nil)
	if err := datastore.Get(ctx, key, &list); err != nil {
		if err == datastore.ErrNoSuchEntity {
			jsonError.NewNotFound("").HttpError(w)
			return
		}
	}

	jsonList, err := json.Marshal(list)
	if err != nil {
		logger.Fatal(err.Error())
		jsonError.NewInternalServerError("").HttpError(w)
		return
	}

	out, err := obj.Apply(jsonList)
	if err != nil {
		jsonError.NewBadRequest("").HttpError(w)
		return
	}

	var patchedList model.List
	if err := json.Unmarshal(out, &patchedList); err != nil {
		jsonError.NewBadRequest("").HttpError(w)
		return
	}

	if _, err := datastore.Put(ctx, key, &patchedList); err != nil {
		logger.Fatal(err.Error())
		jsonError.NewInternalServerError(err.Error()).HttpError(w)
		return
	}

	w.WriteHeader(http.StatusNoContent)
}
Exemple #2
0
func Get(w http.ResponseWriter, r *http.Request) {
	ctx := appengine.NewContext(r)
	listId, err := strconv.ParseInt(mux.Vars(r)["listId"], 10, 64)
	if err != nil {
		jsonError.NewBadRequest(err.Error()).HttpError(w)
		return
	}
	key := datastore.NewKey(ctx, "List", "", listId, nil)

	var list model.List
	if err := datastore.Get(ctx, key, &list); err != nil {
		if err == datastore.ErrNoSuchEntity {
			jsonError.NewNotFound(err.Error())
			return
		}
	}

	enc := json.NewEncoder(w)
	if err := enc.Encode(list); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
}