Exemplo n.º 1
0
// globalIdPut is handler for PUT /companies/{globalId}
// Update existing company. Updating ``globalId`` is not allowed.
func (api CompaniesAPI) globalIdPut(w http.ResponseWriter, r *http.Request) {

	globalID := mux.Vars(r)["globalId"]

	var company companydb.Company

	if err := json.NewDecoder(r.Body).Decode(&company); err != nil {
		http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
		return
	}

	companyMgr := companydb.NewCompanyManager(r)

	oldCompany, cerr := companyMgr.GetByName(globalID)
	if cerr != nil {
		log.Debug(cerr)
		http.Error(w, "Not found", http.StatusNotFound)
		return
	}

	if company.Globalid != globalID || company.GetId() != oldCompany.GetId() {
		http.Error(w, "Changing globalId or id is Forbidden!", http.StatusForbidden)
		return
	}

	if err := companyMgr.Save(&company); err != nil {
		log.Error("Error saving company:\n", err)
		http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
		return
	}

}
Exemplo n.º 2
0
// Post is handler for POST /companies
// Register a new company
func (api CompaniesAPI) Post(w http.ResponseWriter, r *http.Request) {

	var company companydb.Company

	if err := json.NewDecoder(r.Body).Decode(&company); err != nil {
		log.Debug("Error decoding the company:", err)
		http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
		return
	}

	if !company.IsValid() {
		log.Debug("Invalid organization")
		http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
		return
	}

	companyMgr := companydb.NewCompanyManager(r)
	err := companyMgr.Create(&company)
	if err != nil && err != db.ErrDuplicate {
		log.Error("Error saving company:", err.Error())
		http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
		return
	}

	if err == db.ErrDuplicate {
		log.Debug("Duplicate company:", company)
		http.Error(w, http.StatusText(http.StatusConflict), http.StatusConflict)
		return
	}

	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(http.StatusCreated)

	json.NewEncoder(w).Encode(&company)
}