Пример #1
0
func dataid(res http.ResponseWriter, req *http.Request) {
	res.Header().Set("content type", "application/json")
	vars := mux.Vars(req)
	id := vars["id"]
	switch req.Method {
	case "GET":
		emp, ok := emps[id]
		if !ok {
			res.WriteHeader(http.StatusNotFound)
			fmt.Fprint(res, string("data not found"))
		}
		outgoingJSON, error := json.Marshal(emp)
		if error != nil {
			log.Println(error.Error())
			http.Error(res, error.Error(), http.StatusInternalServerError)
			return
		}
		fmt.Fprint(res, string(outgoingJSON))
	case "POST":
		emp := new(operations.Employee)
		decoder := json.NewDecoder(req.Body)
		error := decoder.Decode(&emp)
		if error != nil {
			log.Println(error.Error())
			http.Error(res, error.Error(), http.StatusInternalServerError)
			return
		}
		emp.Insert(emp)
		emps[id] = *emp

		outgoingJSON, err := json.Marshal(emp)
		if err != nil {
			log.Println(error.Error())
			http.Error(res, err.Error(), http.StatusInternalServerError)
			return
		}
		res.WriteHeader(http.StatusCreated)
		fmt.Fprint(res, string(outgoingJSON))
	case "DELETE":
		delete(emps, id)
		//	i,err:=strconv.Atoi(id)
		//	if err!=nil{
		//		log.Fatal(err)
		//	}
		//operations.Delete(i)
		res.WriteHeader(http.StatusNoContent)
	case "PUT":
		emp, ok := emps[id]
		if !ok {
			res.WriteHeader(http.StatusNotFound)
			fmt.Fprint(res, string("data not found to modify"))
		}
		empnew := new(operations.Employee)
		decoder := json.NewDecoder(req.Body)
		error := decoder.Decode(&empnew)
		if error != nil {
			log.Println(error.Error())
			http.Error(res, error.Error(), http.StatusInternalServerError)
			return
		}
		operations.Update(emp.EmpID, empnew.LastName, empnew.FirstName, empnew.Department)
		//emps[id] = emp
		user := new(operations.Employee)
		value, i := user.List()
		k, err := strconv.Atoi(id)
		if err != nil {
			log.Println(error.Error())
			http.Error(res, err.Error(), http.StatusInternalServerError)
			return
		}
		fmt.Println(k)
		for j := 0; j <= i; j++ {
			if value[j].EmpID == k {
				fmt.Println(j, k)
				emp = value[j]
			}
		}
		fmt.Println(emp.FirstName, emp.LastName, emp.EmpID, emp.Department)
		if !ok {
			res.WriteHeader(http.StatusNotFound)
			fmt.Fprint(res, string("data not found to modify"))
		}
		outgoingJSON, error := json.Marshal(emp)
		if error != nil {
			log.Println(error.Error())
			http.Error(res, error.Error(), http.StatusInternalServerError)
			return
		}
		fmt.Fprint(res, string(outgoingJSON))
	}

}