Ejemplo n.º 1
0
func (c *TodoContext) Replace(rw web.ResponseWriter, req *web.Request) {
	todoToUpdate := &Todo{}
	c.UnmarshalBody(rw, req, &todoToUpdate)
	err := c.TodoService.Update(req.PathParams["id"], todoToUpdate)
	if err != nil {
		rw.WriteHeader(http.StatusBadRequest)
		log.Panicln(err)
	}

	rw.WriteHeader(http.StatusOK)
}
Ejemplo n.º 2
0
// Unmarshal request body in JSON to a struct
func (c *Context) UnmarshalBody(rw web.ResponseWriter, req *web.Request, object interface{}) {
	body, err := ioutil.ReadAll(req.Body)
	if err != nil {
		rw.WriteHeader(http.StatusBadRequest)
		log.Panicln(err)
	}

	err = json.Unmarshal(body, object)
	if err != nil {
		rw.WriteHeader(http.StatusBadRequest)
		log.Panicln(err)
	}
}
Ejemplo n.º 3
0
func (c *TodoContext) Create(rw web.ResponseWriter, req *web.Request) {
	todo := &Todo{}
	c.UnmarshalBody(rw, req, &todo)
	todo.Id = ""
	todo.CreatedAt = time.Now()

	id, err := c.TodoService.Create(todo)
	if err != nil {
		rw.WriteHeader(http.StatusBadRequest)
		log.Panicln(err)
	}

	rw.Header().Set("Location", "/todos/"+id)
	rw.WriteHeader(http.StatusCreated)
}
Ejemplo n.º 4
0
func (c *TodoContext) ReadMany(rw web.ResponseWriter, req *web.Request) {
	todos := &Todos{}
	err := c.TodoService.ReadMany(todos)
	if err != nil {
		rw.WriteHeader(http.StatusInternalServerError)
		log.Panicln(err)
	}

	resp, err := json.MarshalIndent(todos, "", "    ")
	if err != nil {
		rw.WriteHeader(http.StatusInternalServerError)
		log.Panicln(err)
	}

	rw.Write(resp)
}
Ejemplo n.º 5
0
func (c *TodoContext) Delete(rw web.ResponseWriter, req *web.Request) {
	err := c.TodoService.Delete(req.PathParams["id"])
	if err != nil {
		switch err := err.(type) {
		case RowNotFoundError:
			rw.WriteHeader(http.StatusNotFound)
		default:
			rw.WriteHeader(http.StatusInternalServerError)
			log.Panicln(err)
		}
	}

	rw.WriteHeader(http.StatusOK)
}
Ejemplo n.º 6
0
func (c *TodoContext) Read(rw web.ResponseWriter, req *web.Request) {
	todo := &Todo{}
	result, err := c.TodoService.Read(req.PathParams["id"], todo)
	if err != nil {
		switch err.(type) {
		case RowNotFoundError:
			rw.WriteHeader(http.StatusNotFound)
		default:
			rw.WriteHeader(http.StatusInternalServerError)
			log.Panicln(err)
		}
	}

	resp, err := json.MarshalIndent(&result, "", "    ")
	if err != nil {
		rw.WriteHeader(http.StatusInternalServerError)
		log.Panicln(err)
	}

	rw.Write(resp)
}