コード例 #1
0
func CreateUser(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json; charset=utf-8")

	var newUser models.NewUser

	body, err := ioutil.ReadAll(io.LimitReader(r.Body, 1048676))

	if err != nil {
		panic(err)
	}

	if err := r.Body.Close(); err != nil {
		panic(err)
	}

	if err := json.Unmarshal(body, &newUser); err != nil {
		message := models.APIMessage{"Input format invalid"}
		json.NewEncoder(w).Encode(message)
	} else {
		var user models.User
		user.Name = newUser.Name
		user.SetEmail(newUser.Email)
		user.SetPassword(newUser.Password)

		database.DB.Create(&user)

		if database.DB.NewRecord(user) {
			message := models.APIMessage{"Error creating user"}

			json.NewEncoder(w).Encode(message)
		} else {
			json.NewEncoder(w).Encode(user)
		}
	}
}
コード例 #2
0
func UpdateUser(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json; charset=utf-8")

	urlParams := mux.Vars(r)
	strID := urlParams["id"]
	user := models.User{}
	var newUser models.NewUser

	id, err := strconv.Atoi(strID)
	if err != nil {
		// handle error
		message := models.APIMessage{"Id format invalid"}
		json.NewEncoder(w).Encode(message)
	} else {

		database.DB.First(&user, id)

		if user.ID == 0 {
			message := models.APIMessage{"User not found"}
			json.NewEncoder(w).Encode(message)
		} else {

			body, err := ioutil.ReadAll(io.LimitReader(r.Body, 1048676))

			if err != nil {
				panic(err)
			}

			if err := r.Body.Close(); err != nil {
				panic(err)
			}

			if err := json.Unmarshal(body, &newUser); err != nil {
				message := models.APIMessage{"Input format invalid"}
				json.NewEncoder(w).Encode(message)
			} else {
				user.Name = newUser.Name
				user.SetEmail(newUser.Email)
				user.SetPassword(newUser.Password)

				database.DB.Save(&user)

				json.NewEncoder(w).Encode(user)
			}
		}
	}
}