Exemplo n.º 1
0
func (c *Comment) PatchItem(w http.ResponseWriter, r *http.Request) {
	bId, _ := strconv.Atoi(mux.Vars(r)["blog"])
	id, _ := strconv.Atoi(mux.Vars(r)["comment"])

	body, err := ioutil.ReadAll(r.Body)
	if err != nil {
		http.Error(w, err.Error(), 500)
		return
	}

	blog := blogsStorage[bId]

	var comment Comment
	for _, comm := range blog.Comments {
		if comm.Id == id {
			comment = comm
			break
		}
	}

	var patch map[string]interface{}
	err = json.Unmarshal(body, &patch)
	if err != nil {
		http.Error(w, err.Error(), 500)
		return
	}

	err = resourceful.PatchStruct(patch, comment, false, false)
	if err != nil {
		http.Error(w, err.Error(), 500)
		return
	}

	url, err := c.ResourceURL("item", "blog", mux.Vars(r)["blog"], "comment", strconv.Itoa(id))
	if err != nil {
		http.Error(w, err.Error(), 500)
		return
	}

	output := struct {
		Comment
		Url string
	}{
		Comment: comment,
		Url:     url.String(),
	}

	out, err := json.Marshal(output)
	if err != nil {
		http.Error(w, err.Error(), 500)
		return
	}

	w.WriteHeader(200)
	fmt.Fprintln(w, out)
}
Exemplo n.º 2
0
func (b *Blog) PatchItem(w http.ResponseWriter, r *http.Request) {
	id, _ := strconv.Atoi(mux.Vars(r)[b.ResourceFullName()])

	body, err := ioutil.ReadAll(r.Body)
	if err != nil {
		http.Error(w, err.Error(), 500)
		return
	}

	blog := blogsStorage[id]

	var patch map[string]interface{}
	err = json.Unmarshal(body, &patch)
	if err != nil {
		http.Error(w, err.Error(), 500)
		return
	}

	err = resourceful.PatchStruct(patch, blog, false, false)
	if err != nil {
		http.Error(w, err.Error(), 500)
		return
	}

	url, err := b.ResourceURL("item", "blog", strconv.Itoa(blog.Id))
	if err != nil {
		http.Error(w, err.Error(), 500)
		return
	}

	blogsStorage[id] = blog

	output := struct {
		Blog
		Url string
	}{
		Blog: blog,
		Url:  url.String(),
	}

	out, err := json.Marshal(output)
	if err != nil {
		http.Error(w, err.Error(), 500)
		return
	}

	w.WriteHeader(200)
	fmt.Fprintln(w, out)
}