Ejemplo n.º 1
0
func Post(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json")

	ctx := appengine.NewContext(r)
	dec := json.NewDecoder(r.Body)

	var list model.List
	if err := dec.Decode(&list); err != nil {
		jsonError.NewBadRequest(err.Error()).HttpError(w)
		return
	}

	key := datastore.NewIncompleteKey(ctx, "List", nil)
	createdAt := time.Now()
	list.Id = key
	list.CreatedAt = createdAt
	list.ModifiedAt = createdAt
	list.Owner = getUser(ctx)

	for _, item := range list.Items {
		item.CreatedAt = createdAt
		item.ModifiedAt = createdAt
	}

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

	enc := json.NewEncoder(w)
	if err := enc.Encode(list); err != nil {
		jsonError.NewInternalServerError(err.Error()).HttpError(w)
		return
	}
}
Ejemplo n.º 2
0
Archivo: patch.go Proyecto: jzorn/lists
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)
}