Example #1
0
func (pC *UsersController) Replace(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	id := ps.ByName("userId")
	if !bson.IsObjectIdHex(id) {
		pC.ServeWithStatus(w, svcSpec.NewErrorResponse().AddCodeError(404), 404)
		return
	}

	decoder := json.NewDecoder(r.Body)
	var u webmsgspec.UpdatedUserResource

	if err := decoder.Decode(&u); err != nil {
		Error.Println(err)
		panic("Failed to decode json:" + err.Error())
	}

	u.Data.ID = id

	if valErrs := validate.ValidateStruct(u); len(valErrs) != 0 {
		errResponse := svcSpec.NewValidationErrorResonse(valErrs)
		pC.ServeWithStatus(w, errResponse, 400)
		return
	}

	inserted, err := pC.userModel.Replace(u.Data)
	if err != nil {
		Error.Println("Error updating user:" + err.Error())
		pC.ServeWithStatus(w, svcSpec.NewErrorResponse().AddCodeError(500), 500)
		return
	}
	pC.ServeWithStatus(w, inserted, 200)
}
Example #2
0
func (pC *UsersController) Create(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	decoder := json.NewDecoder(r.Body)
	var u webmsgspec.NewUserResource

	if err := decoder.Decode(&u); err != nil {
		Error.Println(err)
		panic("Failed to decode json:" + err.Error())
	}

	if valErrs := validate.ValidateStruct(u); len(valErrs) != 0 {
		errResponse := svcSpec.NewValidationErrorResonse(valErrs)
		pC.ServeWithStatus(w, errResponse, 400)
		return
	}

	inserted, err := pC.userModel.Create(u.Data)
	if err != nil {
		Error.Println("Error creating user:" + err.Error())
		pC.ServeWithStatus(w, svcSpec.NewErrorResponse().AddCodeError(500), 500)
		return
	}
	pC.ServeWithStatus(w, inserted, 201)
}