diff --git a/adoptee_handlers.go b/adoptee_handlers.go index 39ab9fa..06d7026 100644 --- a/adoptee_handlers.go +++ b/adoptee_handlers.go @@ -20,10 +20,10 @@ type Adoptee struct { } var adoptees []*Adoptee +var adopteeSeq = intSeq() var createAdopteeHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { adoptee := Adoptee{} - autoIncrement := len(adoptees) err := r.ParseForm() @@ -33,7 +33,7 @@ var createAdopteeHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http. return } - adoptee.ID = autoIncrement + 1 + adoptee.ID = adopteeSeq() adoptee.Name = r.Form.Get("name") adoptee.Breed = r.Form.Get("breed") adoptee.Gender = r.Form.Get("gender") @@ -124,24 +124,3 @@ var deleteAdopteeHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http. } }) - -// Helper Functions - -func getAdopteeByID(id int) (*Adoptee, int) { - var adoptee *Adoptee - var index int - for i, a := range adoptees { - if a.ID == id { - adoptee = a - index = i - } - } - return adoptee, index -} - -func removeAdopteeByID(index int) { - var emptyAdoptee *Adoptee - adoptees[index] = adoptees[len(adoptees)-1] - adoptees[len(adoptees)-1] = emptyAdoptee - adoptees = adoptees[:len(adoptees)-1] -} diff --git a/adopter_handlers.go b/adopter_handlers.go index 1ec2841..5307ba4 100644 --- a/adopter_handlers.go +++ b/adopter_handlers.go @@ -4,92 +4,57 @@ import ( "encoding/json" "fmt" "net/http" - "reflect" "strconv" - "strings" "github.com/gorilla/mux" ) type Adopter struct { - ID int `json:"id"` - FirstName string `json:"first_name"` - LastName string `json:"last_name"` - Phone string `json:"phone"` - Email string `json:"email"` - Gender string `json:"gender"` - Birthdate string `json:"birthdate"` - Address string `json:"address"` - Country string `json:"country"` - State string `json:"state"` - City string `json:"city"` - ZipCode string `json:"zip_code"` - PetPreferences []PetPreference `json:"pet_preferences"` + ID int `json:"id"` + FirstName string `json:"first_name"` + LastName string `json:"last_name"` + Phone string `json:"phone"` + Email string `json:"email"` + Gender string `json:"gender"` + Birthdate string `json:"birthdate"` + Address string `json:"address"` + Country string `json:"country"` + State string `json:"state"` + City string `json:"city"` + ZipCode string `json:"zip_code"` + PetPreferences string `json:"pet_preferences"` +} + +func (a *Adopter) Preferences() []PetPreference { + var prefs []PetPreference + if len(a.PetPreferences) > 0 { + petPrefBytes := []byte(a.PetPreferences) + json.Unmarshal(petPrefBytes, &prefs) + } + return prefs } var adopters []*Adopter +var adopterSeq = intSeq() +var petPrefSeq = intSeq() var createAdopterHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - adopter := Adopter{} - adopterPetPreferences := []PetPreference{} - adopterAutoIncrement := len(adopters) + 1 - petPrefAutoIncrement := len(petPrefs) + 1 - - err := r.ParseForm() - + decoder := json.NewDecoder(r.Body) + var adopter Adopter + err := decoder.Decode(&adopter) if err != nil { fmt.Println(fmt.Errorf("Error: %v", err)) w.WriteHeader(http.StatusInternalServerError) return } - - adopter.ID = adopterAutoIncrement - adopter.FirstName = r.Form.Get("first_name") - adopter.LastName = r.Form.Get("last_name") - adopter.Phone = r.Form.Get("phone") - adopter.Email = r.Form.Get("email") - adopter.Gender = r.Form.Get("gender") - adopter.Birthdate = r.Form.Get("birthdate") - adopter.Address = r.Form.Get("address") - adopter.Country = r.Form.Get("country") - adopter.State = r.Form.Get("state") - adopter.City = r.Form.Get("city") - adopter.ZipCode = r.Form.Get("zipcode") - petPreferenceA := PetPreference{ - petPrefAutoIncrement, - r.Form.Get("pet_preference_a_breed"), - r.Form.Get("pet_preference_a_age"), - r.Form.Get("pet_preference_a_gender"), - } - petPrefAutoIncrement++ - petPreferenceB := PetPreference{ - petPrefAutoIncrement, - r.Form.Get("pet_preference_b_breed"), - r.Form.Get("pet_preference_b_age"), - r.Form.Get("pet_preference_b_gender"), - } - petPrefAutoIncrement++ - petPreferenceC := PetPreference{ - petPrefAutoIncrement, - r.Form.Get("pet_preference_c_breed"), - r.Form.Get("pet_preference_c_age"), - r.Form.Get("pet_preference_c_gender"), - } - petPrefAutoIncrement++ - adopterPetPreferences = append(adopterPetPreferences, petPreferenceA) - adopterPetPreferences = append(adopterPetPreferences, petPreferenceB) - adopterPetPreferences = append(adopterPetPreferences, petPreferenceC) - adopter.PetPreferences = adopterPetPreferences - for _, pref := range adopterPetPreferences { - petPrefs = append(petPrefs, &pref) - } - + adopter.ID = adopterSeq() adopters = append(adopters, &adopter) + for _, pref := range adopter.Preferences() { + petPreferences = append(petPreferences, &pref) + } - // redirect user to original HTML page - // http.Redirect(w, r, "/", http.StatusFound) - payload, _ := json.Marshal(adopters) - w.Write([]byte(payload)) + w.WriteHeader(http.StatusCreated) + json.NewEncoder(w).Encode(adopter) }) @@ -102,25 +67,14 @@ var getAdopterHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Req return } - w.Header().Set("Content-Type", "application/json") adopter, _ := getAdopterByID(id) if adopter != nil { - payload, _ := json.Marshal(adopter) - w.Write([]byte(payload)) - } else { - w.Write([]byte("Adopter Not Found")) + json.NewEncoder(w).Encode(adopter) } - }) var getAdoptersHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - adopterListBytes, err := json.Marshal(adopters) - if err != nil { - fmt.Println(fmt.Errorf("Error: %v", err)) - w.WriteHeader(http.StatusInternalServerError) - return - } - w.Write(adopterListBytes) + json.NewEncoder(w).Encode(adopters) }) var updateAdopterHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { @@ -132,23 +86,32 @@ var updateAdopterHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http. w.Write([]byte("Adopter ID not valid")) return } - - w.Header().Set("Content-Type", "application/json") - adopter, _ := getAdopterByID(id) - if adopter != nil { - requestQuery := r.URL.Query() - for key := range requestQuery { - newKey := formatKey(key) - value := requestQuery.Get(key) - reflect.ValueOf(adopter).Elem().FieldByName(newKey).SetString(value) - } - payload, _ := json.Marshal(adopter) - w.Write([]byte(payload)) - } else { - w.Write([]byte("Adopter Not Found")) + + if adopter == nil { + w.Write([]byte(fmt.Sprintf("Adopter with ID %s not found", id))) + return } + decoder := json.NewDecoder(r.Body) + var updatedAdopter Adopter + err = decoder.Decode(&updatedAdopter) + + if err == nil { + adopter.FirstName = updatedAdopter.FirstName + adopter.LastName = updatedAdopter.LastName + adopter.Phone = updatedAdopter.Phone + adopter.Email = updatedAdopter.Email + adopter.Gender = updatedAdopter.Gender + adopter.Birthdate = updatedAdopter.Birthdate + adopter.Address = updatedAdopter.Address + adopter.Country = updatedAdopter.Country + adopter.State = updatedAdopter.State + adopter.City = updatedAdopter.City + adopter.ZipCode = updatedAdopter.ZipCode + + json.NewEncoder(w).Encode(adopter) + } }) var deleteAdopterHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { @@ -164,42 +127,9 @@ var deleteAdopterHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http. adopter, index := getAdopterByID(id) if adopter != nil { removeAdopterByID(index) - w.Write([]byte("Adopter with ID " + string(index) + " removed")) + fmt.Fprintf(w, "The adopter with ID %v has been deleted successfully", id) } else { - w.Write([]byte("Adopter Not Found")) + fmt.Fprintf(w, "The adopter with ID %v was not found", id) } -}) -// Helper Functions - -func getAdopterByID(id int) (*Adopter, int) { - var adopter *Adopter - var index int - for i, a := range adopters { - if a.ID == id { - adopter = a - index = i - } - } - return adopter, index -} - -func removeAdopterByID(index int) { - var emptyAdopter *Adopter - adopters[index] = adopters[len(adopters)-1] - adopters[len(adopters)-1] = emptyAdopter - adopters = adopters[:len(adopters)-1] -} - -func formatKey(key string) string { - var str string - if strings.Contains(key, "_") { - str = strings.Replace(key, "_", " ", -1) - str = strings.Title(str) - str = strings.Replace(str, " ", "", -1) - - } else { - str = strings.Title(key) - } - return str -} +}) diff --git a/adoption_handlers.go b/adoption_handlers.go index 95ebfbf..7714ff9 100644 --- a/adoption_handlers.go +++ b/adoption_handlers.go @@ -17,6 +17,7 @@ type Adoption struct { } var adoptions []*Adoption +var adoptionSeq = intSeq() var createAdoptionHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) @@ -40,7 +41,7 @@ var createAdoptionHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http return } adoption := Adoption{} - adoption.ID = len(adoptions) + 1 + adoption.ID = adoptionSeq() adoption.Adopter = adopter adoption.Adoptee = adoptee adoptions = append(adoptions, &adoption) @@ -98,24 +99,3 @@ var deleteAdoptionHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http w.Write([]byte("Adoption Not Found")) } }) - -// Helper Functions - -func getAdoptionByID(id int) (*Adoption, int) { - var adoption *Adoption - var index int - for i, a := range adoptions { - if a.ID == id { - adoption = a - index = i - } - } - return adoption, index -} - -func removeAdoptionByID(index int) { - var emptyAdoption *Adoption - adoptions[index] = adoptions[len(adoptions)-1] - adoptions[len(adoptions)-1] = emptyAdoption - adoptions = adoptions[:len(adoptions)-1] -} diff --git a/helpers.go b/helpers.go new file mode 100644 index 0000000..bacc767 --- /dev/null +++ b/helpers.go @@ -0,0 +1,100 @@ +package main + +import "strings" + +func getAdopterByID(id int) (*Adopter, int) { + var adopter *Adopter + var index int + for i, a := range adopters { + if a.ID == id { + adopter = a + index = i + } + } + return adopter, index +} + +func removeAdopterByID(index int) { + var emptyAdopter *Adopter + adopters[index] = adopters[len(adopters)-1] + adopters[len(adopters)-1] = emptyAdopter + adopters = adopters[:len(adopters)-1] +} + +func getAdopteeByID(id int) (*Adoptee, int) { + var adoptee *Adoptee + var index int + for i, a := range adoptees { + if a.ID == id { + adoptee = a + index = i + } + } + return adoptee, index +} + +func removeAdopteeByID(index int) { + var emptyAdoptee *Adoptee + adoptees[index] = adoptees[len(adoptees)-1] + adoptees[len(adoptees)-1] = emptyAdoptee + adoptees = adoptees[:len(adoptees)-1] +} + +func getAdoptionByID(id int) (*Adoption, int) { + var adoption *Adoption + var index int + for i, a := range adoptions { + if a.ID == id { + adoption = a + index = i + } + } + return adoption, index +} + +func removeAdoptionByID(index int) { + var emptyAdoption *Adoption + adoptions[index] = adoptions[len(adoptions)-1] + adoptions[len(adoptions)-1] = emptyAdoption + adoptions = adoptions[:len(adoptions)-1] +} + +func getPetPreferenceByID(id int) (*PetPreference, int) { + var petPreference *PetPreference + var index int + for i, p := range petPreferences { + if p.ID == id { + petPreference = p + index = i + } + } + return petPreference, index +} + +func removePetPreferenceByID(index int) { + var emptyPetPreference *PetPreference + petPreferences[index] = petPreferences[len(petPreferences)-1] + petPreferences[len(petPreferences)-1] = emptyPetPreference + petPreferences = petPreferences[:len(petPreferences)-1] +} + +func formatKey(key string) string { + var str string + if strings.Contains(key, "_") { + str = strings.Replace(key, "_", " ", -1) + str = strings.Title(str) + str = strings.Replace(str, " ", "", -1) + + } else { + str = strings.Title(key) + } + return str +} + +func intSeq() func() int { + i := 0 + return func() int { + i++ + return i + } +} diff --git a/main.go b/main.go index 0c3fe46..bcb2225 100644 --- a/main.go +++ b/main.go @@ -19,23 +19,24 @@ func main() { r.Handle("/adopter", createAdopterHandler).Methods("POST") r.Handle("/adopters", getAdoptersHandler).Methods("GET") r.Handle("/adopter/{id}", getAdopterHandler).Methods("GET") - r.Handle("/adopter/{id}/update", updateAdopterHandler).Methods("GET") - r.Handle("/adopter/{id}/delete", deleteAdopterHandler).Methods("GET") + r.Handle("/adopter/{id}", updateAdopterHandler).Methods("PATCH") + r.Handle("/adopter/{id}", deleteAdopterHandler).Methods("DELETE") - r.Handle("/adoptee", createAdopteeHandler).Methods("GET") + r.Handle("/adoptee", createAdopteeHandler).Methods("POST") r.Handle("/adoptees", getAdopteesHandler).Methods("GET") r.Handle("/adoptee/{id}", getAdopteeHandler).Methods("GET") - r.Handle("/adoptee/{id}/update", updateAdopteeHandler).Methods("GET") - r.Handle("/adoptees/{id}/delete", deleteAdopteeHandler).Methods("GET") + r.Handle("/adoptee/{id}/update", updateAdopteeHandler).Methods("PATCH") + r.Handle("/adoptees/{id}/delete", deleteAdopteeHandler).Methods("DELETE") - r.Handle("/petpref", createPetPreferenceHandler).Methods("GET") + r.Handle("/petpref", createPetPreferenceHandler).Methods("POST") r.Handle("/petprefs", getPetPreferencesHandler).Methods("GET") - r.Handle("/petpref/{id}/update", updatePetPrefenceHandler).Methods("GET") - r.Handle("/petpref/{id}/delete", deletePetPreferenceHandler).Methods("GET") + r.Handle("/petpref/{id}/update", updatePetPrefenceHandler).Methods("PATCH") + r.Handle("/petpref/{id}", deletePetPreferenceHandler).Methods("DELETE") - r.Handle("/adoption/adopter/{adopter_id}/adoptee/{adoptee_id}", createAdoptionHandler).Methods("GET") + r.Handle("/adoption", createAdoptionHandler).Methods("POST") r.Handle("/adoptions", getAdoptionsHandler).Methods("GET") r.Handle("/adoption/{id}", getAdoptionHandler).Methods("GET") + r.Handle("/adoption/{id}", deleteAdoptionHandler).Methods("DELETE") http.ListenAndServe(":3000", handlers.LoggingHandler(os.Stdout, r)) diff --git a/petpreference_handlers.go b/petpreference_handlers.go index c44c78b..eb4040d 100644 --- a/petpreference_handlers.go +++ b/petpreference_handlers.go @@ -17,11 +17,12 @@ type PetPreference struct { Gender string `json:"gender"` } -var petPrefs []*PetPreference +var petPreferences []*PetPreference +var petPreferenceSeq = intSeq() var createPetPreferenceHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { petPreference := PetPreference{} - petPreference.ID = len(petPrefs) + 1 + petPreference.ID = petPreferenceSeq() requestQuery := r.URL.Query() for key := range requestQuery { @@ -35,13 +36,13 @@ var createPetPreferenceHandler = http.HandlerFunc(func(w http.ResponseWriter, r petPreference.Gender = value } } - petPrefs = append(petPrefs, &petPreference) + petPreferences = append(petPreferences, &petPreference) payload, _ := json.Marshal(petPreference) w.Write([]byte(payload)) }) var getPetPreferencesHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - petPrefsListBytes, err := json.Marshal(petPrefs) + petPrefsListBytes, err := json.Marshal(petPreferences) if err != nil { fmt.Println(fmt.Errorf("Error: %v", err)) w.WriteHeader(http.StatusInternalServerError) @@ -94,24 +95,3 @@ var deletePetPreferenceHandler = http.HandlerFunc(func(w http.ResponseWriter, r w.Write([]byte("Pet Preference Not Found")) } }) - -// Helper Functions - -func getPetPreferenceByID(id int) (*PetPreference, int) { - var petPreference *PetPreference - var index int - for i, p := range petPrefs { - if p.ID == id { - petPreference = p - index = i - } - } - return petPreference, index -} - -func removePetPreferenceByID(index int) { - var emptyPetPreference *PetPreference - petPrefs[index] = petPrefs[len(petPrefs)-1] - petPrefs[len(petPrefs)-1] = emptyPetPreference - petPrefs = petPrefs[:len(petPrefs)-1] -}