Beispiel #1
0
// curl -XPOST -H 'Content-Type: application/json' -d '{"company": "Google", "city": "New York", "state": "New York", "Country": "USA", "Base": 136000, "Bonus": "20%", "Perks": 20000, "Stack": ["linux", "mysql", "apache", "php"]}' http://localhost:3000/api/salaryData
// SalaryDataCreate handler.
func (c *salaryDataController) SalaryDataCreate(w http.ResponseWriter, r *http.Request) (error, int) {

	// Create a new SalaryData struct and set the DateAdded.
	s := models.SalaryData{}
	s.DateAdded = time.Now()

	// hah, err := ioutil.ReadAll(r.Body)
	// if err != nil {
	// 	fmt.Printf("%s", err)
	// }
	// fmt.Printf("%s", hah)

	// Decode the JSON onto the struct.
	err := json.NewDecoder(r.Body).Decode(&s)
	if err != nil {
		return err, http.StatusInternalServerError
	}

	// * Is there any validation we should do here?
	// Create the item via the DB Service.
	err = c.databaseService.Create(s)
	if err != nil {
		return err, http.StatusInternalServerError
	}

	// Get and return all the salaries after creation.
	// * Should set the 20 here as config for the default number to show
	ss, err := c.databaseService.FindN(20, "", false)
	if err != nil {
		return err, http.StatusNotFound
	}

	// Marshal the documents as JSON.
	json, err := json.Marshal(ss)
	if err != nil {
		return err, http.StatusInternalServerError
	}

	// Write the JSON to the response.
	w.Header().Set("Content-Type", "application/json")
	w.Write(json)

	return nil, http.StatusCreated
}