Exemplo n.º 1
0
func CreateClient(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json; charset=utf-8")

	var newClient models.NewClient

	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, &newClient); err != nil {
		message := models.APIMessage{"Input format invalid"}
		json.NewEncoder(w).Encode(message)
	} else {
		var client models.Client
		client.Name = newClient.Name
		client.GenerateKeys()

		database.DB.Create(&client)

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

			json.NewEncoder(w).Encode(message)
		} else {
			json.NewEncoder(w).Encode(client)
		}
	}
}
Exemplo n.º 2
0
func UpdateClient(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json; charset=utf-8")

	urlParams := mux.Vars(r)
	strID := urlParams["id"]
	client := models.Client{}
	var newClient models.NewClient

	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(&client, id)

		if client.ID == 0 {
			message := models.APIMessage{"Client 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, &newClient); err != nil {
				message := models.APIMessage{"Input format invalid"}
				json.NewEncoder(w).Encode(message)
			} else {
				client.Name = newClient.Name

				database.DB.Save(&client)

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