Exemple #1
0
func IndexAction(w http.ResponseWriter, r *http.Request, newsModel *news.NewsRepository) {
	w.Header().Set("Content-Type", "application/json; charset=UTF-8")
	news, err := newsModel.GetNews()
	if err != nil {
		w.WriteHeader(http.StatusInternalServerError)
		return
	}
	w.WriteHeader(http.StatusOK)

	if err := json.NewEncoder(w).Encode(news); err != nil {
		panic(err)
	}
}
Exemple #2
0
func CreateAction(w http.ResponseWriter, r *http.Request, newsModel *news.NewsRepository) {
	var news news.News
	body, err := ioutil.ReadAll(io.LimitReader(r.Body, 1048576))
	if err != nil {
		panic(err)
	}
	if err := r.Body.Close(); err != nil {
		panic(err)
	}
	if err := json.Unmarshal(body, &news); err != nil {
		w.Header().Set("Content-Type", "application/json; charset=UTF-8")
		w.WriteHeader(422) // unprocessable entity
		if err := json.NewEncoder(w).Encode(err); err != nil {
			panic(err)
		}
	}
	newsModel.CreateNews(news)
	w.Header().Set("Content-Type", "application/json; charset=UTF-8")
	w.WriteHeader(http.StatusCreated)
	if err := json.NewEncoder(w).Encode(news); err != nil {
		panic(err)
	}
}