示例#1
0
文件: todos.go 项目: ottogiron/gotodo
func handlePOST(w http.ResponseWriter, r *http.Request) {
	body, err := ioutil.ReadAll(io.LimitReader(r.Body, 1048576))
	if err != nil {
		panic(err)
	}

	todo := models.NewTodo()
	if err := json.Unmarshal(body, todo); err != nil {
		w.Header().Set("Content-Type", "application/vnd.api+json")
		w.WriteHeader(422) // unprocessable entity
		if err := json.NewEncoder(w).Encode(err); err != nil {
			panic(err)
		}
	}

	session, err := createMongoSession()
	defer session.Close()
	if err != nil {
		handleServerError(w, err)
		return
	}

	collection := getTodoCollection(session)
	if r.Method == "POST" {
		collection.Insert(todo)
	} else {
		//it's PATCH
		vars := server.Vars(r)
		id := vars["id"]
		collection.UpdateId(bson.ObjectIdHex(id), todo)
	}
	json.NewEncoder(w).Encode(todo)
}
示例#2
0
文件: todos.go 项目: ottogiron/gotodo
func handleDELETE(w http.ResponseWriter, r *http.Request) {
	vars := server.Vars(r)
	id := vars["id"]
	session, err := createMongoSession()
	defer session.Close()
	if err != nil {
		handleServerError(w, err)
		return
	}
	w.WriteHeader(http.StatusNoContent)
	collection := getTodoCollection(session)
	collection.RemoveId(bson.ObjectIdHex(id))
}