Beispiel #1
0
func updateArticle(ctx context.Context, w http.ResponseWriter, r *http.Request) {
	article, ok := ctx.Value("article").(*Article)
	if !ok {
		http.Error(w, http.StatusText(404), 404)
		return
	}

	// btw, you could do this body reading / marhsalling in a nice bind middleware
	data, err := ioutil.ReadAll(r.Body)
	if err != nil {
		http.Error(w, err.Error(), 422)
		return
	}
	defer r.Body.Close()

	uArticle := struct {
		*Article
		_ interface{} `json:"id,omitempty"` // prevents 'id' from being overridden
	}{Article: article}

	if err := json.Unmarshal(data, &uArticle); err != nil {
		http.Error(w, err.Error(), 422)
		return
	}

	render.JSON(w, 200, uArticle)

	// w.Write([]byte(fmt.Sprintf("updated article, title:%s", uArticle.Title)))
}
Beispiel #2
0
func getArticle(ctx context.Context, w http.ResponseWriter, r *http.Request) {
	article, ok := ctx.Value("article").(*Article)
	if !ok {
		http.Error(w, http.StatusText(422), 422)
		return
	}

	// Build your own responder, see the "./render" pacakge as a starting
	// point for your own.
	render.JSON(w, 200, article)

	// or..
	// w.Write([]byte(fmt.Sprintf("title:%s", article.Title)))
}