diff --git a/adoptee.go b/adoptee.go
new file mode 100644
index 0000000..18d96f4
--- /dev/null
+++ b/adoptee.go
@@ -0,0 +1,108 @@
+package main
+
+import (
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "strconv"
+
+ "github.com/gorilla/mux"
+)
+
+type Adoptee struct {
+ ID int `json:"id"`
+ Name string `json:"name"`
+ Breed string `json:"breed"`
+ Gender string `json:"gender"`
+ Age string `json:"age"`
+}
+
+func (ar *AnimalRescue) CreateAdoptee(w http.ResponseWriter, r *http.Request) {
+ decoder := json.NewDecoder(r.Body)
+ adoptee := new(Adoptee)
+ err := decoder.Decode(adoptee)
+ if err != nil {
+ fmt.Println(fmt.Errorf("Error: %v", err))
+ w.WriteHeader(http.StatusInternalServerError)
+ return
+ }
+
+ adoptee.ID = ar.AdopteeSeq()
+ ar.Adoptees = append(ar.Adoptees, adoptee)
+ w.WriteHeader(http.StatusCreated)
+ json.NewEncoder(w).Encode(adoptee)
+
+}
+
+func (ar *AnimalRescue) GetAdoptee(w http.ResponseWriter, r *http.Request) {
+ vars := mux.Vars(r)
+ id, err := strconv.Atoi(vars["id"])
+
+ if err != nil {
+ w.Write([]byte("Adoptee ID not valid"))
+ return
+ }
+
+ w.Header().Set("Content-Type", "application/json")
+
+ adoptee, _ := ar.GetAdopteeByID(id)
+ if adoptee != nil {
+ payload, _ := json.Marshal(adoptee)
+ w.Write([]byte(payload))
+ } else {
+ w.Write([]byte("Adoptee Not Found"))
+ }
+
+}
+
+func (ar *AnimalRescue) GetAdoptees(w http.ResponseWriter, r *http.Request) {
+ json.NewEncoder(w).Encode(ar.Adoptees)
+}
+
+func (ar *AnimalRescue) UpdateAdoptee(w http.ResponseWriter, r *http.Request) {
+ // GET adoptee and update fields
+ vars := mux.Vars(r)
+ id, err := strconv.Atoi(vars["id"])
+
+ if err != nil {
+ w.Write([]byte("Adoptee ID not valid"))
+ return
+ }
+ adoptee, _ := ar.GetAdopteeByID(id)
+
+ if adoptee == nil {
+ w.Write([]byte(fmt.Sprintf("Adoptee with ID %d not found", id)))
+ return
+ }
+
+ decoder := json.NewDecoder(r.Body)
+ updatedAdoptee := new(Adoptee)
+ err = decoder.Decode(updatedAdoptee)
+
+ if err == nil {
+ updatedAdoptee.ID = id
+ *adoptee = *updatedAdoptee
+ json.NewEncoder(w).Encode(adoptee)
+ }
+
+}
+
+func (ar *AnimalRescue) DeleteAdoptee(w http.ResponseWriter, r *http.Request) {
+ // GET adoptee and remove from list stored in memory
+ vars := mux.Vars(r)
+ id, err := strconv.Atoi(vars["id"])
+
+ if err != nil {
+ w.Write([]byte("Adoptee ID not valid"))
+ return
+ }
+
+ adoptee, index := ar.GetAdopteeByID(id)
+ if adoptee != nil {
+ ar.RemoveAdopteeByID(index)
+ fmt.Fprintf(w, "The adoptee with ID %v has been deleted successfully", id)
+ } else {
+ fmt.Fprintf(w, "The adoptee with ID %v was not found", id)
+ }
+
+}
diff --git a/adoptee_handlers.go b/adoptee_handlers.go
deleted file mode 100644
index 06d7026..0000000
--- a/adoptee_handlers.go
+++ /dev/null
@@ -1,126 +0,0 @@
-package main
-
-import (
- "encoding/json"
- "fmt"
- "net/http"
- "reflect"
- "strconv"
- "strings"
-
- "github.com/gorilla/mux"
-)
-
-type Adoptee struct {
- ID int `json:"id"`
- Name string `json:"name"`
- Breed string `json:"breed"`
- Gender string `json:"gender"`
- Age string `json:"age"`
-}
-
-var adoptees []*Adoptee
-var adopteeSeq = intSeq()
-
-var createAdopteeHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- adoptee := Adoptee{}
-
- err := r.ParseForm()
-
- if err != nil {
- fmt.Println(fmt.Errorf("Error: %v", err))
- w.WriteHeader(http.StatusInternalServerError)
- return
- }
-
- adoptee.ID = adopteeSeq()
- adoptee.Name = r.Form.Get("name")
- adoptee.Breed = r.Form.Get("breed")
- adoptee.Gender = r.Form.Get("gender")
- adoptee.Age = r.Form.Get("age")
-
- adoptees = append(adoptees, &adoptee)
- payload, _ := json.Marshal(adoptees)
- w.Write([]byte(payload))
-
-})
-
-var getAdopteeHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- vars := mux.Vars(r)
- id, err := strconv.Atoi(vars["id"])
-
- if err != nil {
- w.Write([]byte("Adoptee ID not valid"))
- return
- }
-
- w.Header().Set("Content-Type", "application/json")
-
- adoptee, _ := getAdopteeByID(id)
- if adoptee != nil {
- payload, _ := json.Marshal(adoptee)
- w.Write([]byte(payload))
- } else {
- w.Write([]byte("Adoptee Not Found"))
- }
-
-})
-
-var getAdopteesHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- adopteeListBytes, err := json.Marshal(adoptees)
-
- if err != nil {
- fmt.Println(fmt.Errorf("Error: %v", err))
- w.WriteHeader(http.StatusInternalServerError)
- return
- }
- w.Write(adopteeListBytes)
-})
-
-var updateAdopteeHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- // GET adoptee and update fields
- vars := mux.Vars(r)
- id, err := strconv.Atoi(vars["id"])
-
- if err != nil {
- w.Write([]byte("Adoptee ID not valid"))
- return
- }
-
- w.Header().Set("Content-Type", "application/json")
-
- adoptee, _ := getAdopteeByID(id)
- if adoptee != nil {
- requestQuery := r.URL.Query()
- for key := range requestQuery {
- newKey := strings.Title(key)
- value := requestQuery.Get(key)
- reflect.ValueOf(adoptee).Elem().FieldByName(newKey).SetString(value)
- }
- payload, _ := json.Marshal(adoptee)
- w.Write([]byte(payload))
- } else {
- w.Write([]byte("Adoptee Not Found"))
- }
-
-})
-
-var deleteAdopteeHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- // GET adoptee and remove from list stored in memory
- vars := mux.Vars(r)
- id, err := strconv.Atoi(vars["id"])
-
- if err != nil {
- w.Write([]byte("Adoptee ID not valid"))
- return
- }
-
- adoptee, index := getAdopteeByID(id)
- if adoptee != nil {
- removeAdopteeByID(index)
- w.Write([]byte("Adoptee with ID " + string(index) + " removed"))
- } else {
- w.Write([]byte("Adoptee Not Found"))
- }
-
-})
diff --git a/adoptee_handlers_test.go b/adoptee_handlers_test.go
deleted file mode 100644
index e228786..0000000
--- a/adoptee_handlers_test.go
+++ /dev/null
@@ -1,99 +0,0 @@
-package main
-
-import (
- "bytes"
- "encoding/json"
- "net/http"
- "net/http/httptest"
- "net/url"
- "strconv"
- "testing"
-)
-
-func TestGetAdopteesHandler(t *testing.T) {
- adoptees := []Adoptee{
- {1, "Callie", "Australian Shepherd", "female", "puppy"},
- }
- // CREATE Adoptee
- form := newCreateAdopteeForm()
- responseRecorder, err := createAdoptee(form)
- if err != nil {
- t.Fatal(err)
- }
- if status := responseRecorder.Code; status != http.StatusFound {
- t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusFound)
- }
-
- // GET Adoptee
- req, err := http.NewRequest("GET", "", nil)
- if err != nil {
- t.Fatal(err)
- }
- recorder := httptest.NewRecorder()
- hf := http.HandlerFunc(getAdopteesHandler)
- hf.ServeHTTP(recorder, req)
-
- if status := recorder.Code; status != http.StatusOK {
- t.Errorf("handler returned wrong status code: got %v want %v",
- status, http.StatusOK)
- }
-
- a := []Adoptee{}
- err = json.NewDecoder(recorder.Body).Decode(&a)
- actual := a[0]
- expected := adoptees[0]
-
- if actual != expected {
- t.Errorf("handler returned unexpected body: got %v want %v", actual, expected)
- }
-
-}
-
-func TestCreateAdopteesHandler(t *testing.T) {
- form := newCreateAdopteeForm()
- responseRecorder, err := createAdoptee(form)
- if err != nil {
- t.Fatal(err)
- }
- if status := responseRecorder.Code; status != http.StatusFound {
- t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusFound)
- }
-
- a := []Adoptee{}
- err = json.NewDecoder(responseRecorder.Body).Decode(&a)
-
- if len(a) != 0 {
- t.Errorf("handler returned unexpected body: got %v want %v", a, []Adoptee{})
- }
-}
-
-func newCreateAdopteeForm() *url.Values {
- form := url.Values{}
- form.Set("id", "1")
- form.Set("name", "Callie")
- form.Set("breed", "Australian Shepherd")
- form.Set("gender", "female")
- form.Set("age", "puppy")
-
- return &form
-
-}
-
-func createAdoptee(form *url.Values) (*httptest.ResponseRecorder, error) {
-
- req, err := http.NewRequest("POST", "", bytes.NewBufferString(form.Encode()))
-
- if err != nil {
- return nil, err
- }
-
- req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
- req.Header.Add("Content-Length", strconv.Itoa(len(form.Encode())))
-
- recorder := httptest.NewRecorder()
- hf := http.HandlerFunc(createAdopteeHandler)
- hf.ServeHTTP(recorder, req)
-
- return recorder, nil
-
-}
diff --git a/adopter_handlers.go b/adopter.go
similarity index 54%
rename from adopter_handlers.go
rename to adopter.go
index 5307ba4..4ce7b7a 100644
--- a/adopter_handlers.go
+++ b/adopter.go
@@ -25,40 +25,40 @@ type Adopter struct {
PetPreferences string `json:"pet_preferences"`
}
-func (a *Adopter) Preferences() []PetPreference {
- var prefs []PetPreference
+func (a *Adopter) Preferences() []*PetPreference {
+ var prefs []*PetPreference
if len(a.PetPreferences) > 0 {
petPrefBytes := []byte(a.PetPreferences)
- json.Unmarshal(petPrefBytes, &prefs)
+ if err := json.Unmarshal(petPrefBytes, &prefs); err != nil {
+ panic(err)
+ }
}
return prefs
}
-var adopters []*Adopter
-var adopterSeq = intSeq()
-var petPrefSeq = intSeq()
-
-var createAdopterHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+func (ar *AnimalRescue) CreateAdopter(w http.ResponseWriter, r *http.Request) {
decoder := json.NewDecoder(r.Body)
- var adopter Adopter
- err := decoder.Decode(&adopter)
+ adopter := new(Adopter)
+ err := decoder.Decode(adopter)
if err != nil {
fmt.Println(fmt.Errorf("Error: %v", err))
w.WriteHeader(http.StatusInternalServerError)
return
}
- adopter.ID = adopterSeq()
- adopters = append(adopters, &adopter)
+ adopter.ID = ar.AdopterSeq()
+ ar.Adopters = append(ar.Adopters, adopter)
+
for _, pref := range adopter.Preferences() {
- petPreferences = append(petPreferences, &pref)
+ ar.PetPreferences = append(ar.PetPreferences, pref)
+
}
w.WriteHeader(http.StatusCreated)
json.NewEncoder(w).Encode(adopter)
-})
+}
-var getAdopterHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+func (ar *AnimalRescue) GetAdopter(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
id, err := strconv.Atoi(vars["id"])
@@ -67,17 +67,17 @@ var getAdopterHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Req
return
}
- adopter, _ := getAdopterByID(id)
+ adopter, _ := ar.GetAdopterByID(id)
if adopter != nil {
json.NewEncoder(w).Encode(adopter)
}
-})
+}
-var getAdoptersHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- json.NewEncoder(w).Encode(adopters)
-})
+func (ar *AnimalRescue) GetAdopters(w http.ResponseWriter, r *http.Request) {
+ json.NewEncoder(w).Encode(ar.Adopters)
+}
-var updateAdopterHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+func (ar *AnimalRescue) UpdateAdopter(w http.ResponseWriter, r *http.Request) {
// GET adopter and update fields
vars := mux.Vars(r)
id, err := strconv.Atoi(vars["id"])
@@ -86,35 +86,24 @@ var updateAdopterHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.
w.Write([]byte("Adopter ID not valid"))
return
}
- adopter, _ := getAdopterByID(id)
+ adopter, _ := ar.GetAdopterByID(id)
if adopter == nil {
- w.Write([]byte(fmt.Sprintf("Adopter with ID %s not found", id)))
+ w.Write([]byte(fmt.Sprintf("Adopter with ID %d not found", id)))
return
}
decoder := json.NewDecoder(r.Body)
- var updatedAdopter Adopter
- err = decoder.Decode(&updatedAdopter)
-
+ updatedAdopter := new(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
-
+ updatedAdopter.ID = id
+ *adopter = *updatedAdopter
json.NewEncoder(w).Encode(adopter)
}
-})
+}
-var deleteAdopterHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+func (ar *AnimalRescue) DeleteAdopter(w http.ResponseWriter, r *http.Request) {
// GET adopter and remove from list stored in memory
vars := mux.Vars(r)
id, err := strconv.Atoi(vars["id"])
@@ -124,12 +113,11 @@ var deleteAdopterHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.
return
}
- adopter, index := getAdopterByID(id)
+ adopter, index := ar.GetAdopterByID(id)
if adopter != nil {
- removeAdopterByID(index)
+ ar.RemoveAdopterByID(index)
fmt.Fprintf(w, "The adopter with ID %v has been deleted successfully", id)
} else {
fmt.Fprintf(w, "The adopter with ID %v was not found", id)
}
-
-})
+}
diff --git a/adopter_handlers_test.go b/adopter_handlers_test.go
deleted file mode 100644
index aeedbee..0000000
--- a/adopter_handlers_test.go
+++ /dev/null
@@ -1,120 +0,0 @@
-package main
-
-import (
- "encoding/json"
- "net/url"
- "testing"
-)
-
-func TestGetAdoptersHandler(t *testing.T) {
- // petPreference := PetPreference{"Australian Shepherd", "puppy", "male"}
- // petPreferenceMarshalled, err := json.Marshal(petPreference)
- // petPreferenceStr := string(petPreferenceMarshalled)
- // var petPreferences []string
- // petPreferences = append(petPreferences, petPreferenceStr)
-
- // adopters = []Adopter{
- // {"Angie", "Pinilla", "973.971.9690", "littledoglover@gmail.com", "Female", "09/11/1992", "444 Leonard St",
- // "USA", "NY", "Brooklyn", "11222", petPreferences},
- // }
-
- // req, err := http.NewRequest("GET", "", nil)
-
- // if err != nil {
- // t.Fatal(err)
- // }
-
- // recorder := httptest.NewRecorder()
-
- // hf := http.HandlerFunc(getAdopterHandler)
- // hf.ServeHTTP(recorder, req)
-
- // if status := recorder.Code; status != http.StatusOK {
- // t.Errorf("handler returned wrong status code: got %v want %v",
- // status, http.StatusOK)
- // }
-
- // expected := adopters[0]
- // a := []Adopter{}
- // err = json.NewDecoder(recorder.Body).Decode(&a)
-
- // if err != nil {
- // t.Fatal(err)
- // }
-
- // actual := a[0]
-
- // if actual != expected {
- // t.Errorf("handler returned unexpected body: got %v want %v", actual, expected)
- // }
-
-}
-
-func TestCreateAdoptersHandler(t *testing.T) {
- // petPreference := PetPreference{"Australian Shepherd", "puppy", "male"}
- // petPreferenceMarshalled, err := json.Marshal(petPreference)
- // petPreferenceStr := string(petPreferenceMarshalled)
- // var petPreferences []string
- // petPreferences = append(petPreferences, petPreferenceStr)
-
- // adopters = []Adopter{
- // {"Angie", "Pinilla", "973.971.9690", "littledoglover@gmail.com", "Female", "09/11/1992", "444 Leonard St",
- // "USA", "NY", "Brooklyn", "11222", petPreferences},
- // }
- // form := newCreateAdopterForm()
- // req, err := http.NewRequest("POST", "", bytes.NewBufferString(form.Encode()))
-
- // if err != nil {
- // t.Fatal(err)
- // }
-
- // req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
- // req.Header.Add("Content-Length", strconv.Itoa(len(form.Encode())))
-
- // recorder := httptest.NewRecorder()
- // hf := http.HandlerFunc(createAdopterHandler)
- // hf.ServeHTTP(recorder, req)
-
- // if status := recorder.Code; status != http.StatusOK {
- // t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusOK)
- // }
-
- // expected := adopters[0]
-
- // if err != nil {
- // t.Fatal(err)
- // }
-
- // actual := adopters[1]
- // if actual != expected {
- // t.Errorf("handler returned unexpected body: got %v want %v", actual, expected)
- // }
-}
-
-func newCreateAdopterForm(t *testing.T) *url.Values {
- form := url.Values{}
- form.Set("first_name", "Angie")
- form.Set("last_name", "Pinilla")
- form.Set("phone", "973.971.9690")
- form.Set("email", "littledoglover@gmail.com")
- form.Set("gender", "Female")
- form.Set("birthdate", "09/11/1992")
- form.Set("address", "444 Leonard St")
- form.Set("country", "USA")
- form.Set("state", "NY")
- form.Set("city", "Brooklyn")
- form.Set("zip_code", "11222")
-
- var petPreferences []PetPreference
- petPreference := PetPreference{"Australian Shepherd", "puppy", "male"}
- petPreferences = append(petPreferences, petPreference)
- petPreferencesMarshalled, err := json.Marshal(petPreferences)
- if err != nil {
- t.Fatal(err)
- }
- petPreferenceStr := string(petPreferencesMarshalled)
- form.Set("pet_preferences", petPreferenceStr)
-
- return &form
-
-}
diff --git a/adopter_test.go b/adopter_test.go
new file mode 100644
index 0000000..9808e0b
--- /dev/null
+++ b/adopter_test.go
@@ -0,0 +1,47 @@
+package main
+
+import (
+ "reflect"
+ "testing"
+)
+
+func TestCreateAdopter(t *testing.T) {
+
+}
+
+func TestGetAdopter(t *testing.T) {
+
+}
+
+func TestGetAdopters(t *testing.T) {
+
+}
+
+func TestUpdateAdopter(t *testing.T) {
+
+}
+
+func TestDeleteAdopter(t *testing.T) {
+
+}
+
+func TestAdopterPetPreferences(t *testing.T) {
+ animalRescue := new(AnimalRescue)
+ animalRescue.init()
+ adopter := new(Adopter)
+ adopter.PetPreferences = `[{"id":1, "breed":"Daschound","age":"Puppy","gender":"Male"}]`
+ expected := make([]*PetPreference, 0)
+ petPref := &PetPreference{
+ ID: 1,
+ Breed: "Daschound",
+ Age: "Puppy",
+ Gender: "Male",
+ }
+ expected = append(expected, petPref)
+ expectedPref := expected[0]
+ actualPref := adopter.Preferences()[0]
+ if !reflect.DeepEqual(actualPref, expectedPref) {
+ t.Errorf("Adopter's PetPreference = %v; expected %v", actualPref, expectedPref)
+ }
+
+}
diff --git a/adoption.go b/adoption.go
new file mode 100644
index 0000000..78816b4
--- /dev/null
+++ b/adoption.go
@@ -0,0 +1,72 @@
+package main
+
+import (
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "strconv"
+
+ "github.com/gorilla/mux"
+)
+
+type Adoption struct {
+ ID int `json:"id"`
+ Adopter *Adopter `json:"adopter"`
+ Adoptee *Adoptee `json:"adoptee"`
+ Date string `json:"date"`
+}
+
+func (ar *AnimalRescue) CreateAdoption(w http.ResponseWriter, r *http.Request) {
+ decoder := json.NewDecoder(r.Body)
+ adoption := new(Adoption)
+ err := decoder.Decode(adoption)
+ if err != nil {
+ fmt.Println(fmt.Errorf("Error: %v", err))
+ w.WriteHeader(http.StatusInternalServerError)
+ return
+ }
+ adoption.ID = ar.AdoptionSeq()
+ ar.Adoptions = append(ar.Adoptions, adoption)
+
+ w.WriteHeader(http.StatusCreated)
+ json.NewEncoder(w).Encode(adoption)
+
+}
+
+func (ar *AnimalRescue) GetAdoption(w http.ResponseWriter, r *http.Request) {
+ vars := mux.Vars(r)
+ id, err := strconv.Atoi(vars["id"])
+
+ if err != nil {
+ w.Write([]byte("Adoption ID not valid"))
+ return
+ }
+
+ adoption, _ := ar.GetAdoptionByID(id)
+ if adoption != nil {
+ json.NewEncoder(w).Encode(adoption)
+ }
+}
+
+func (ar *AnimalRescue) GetAdoptions(w http.ResponseWriter, r *http.Request) {
+ json.NewEncoder(w).Encode(ar.Adoptions)
+}
+
+func (ar *AnimalRescue) DeleteAdoption(w http.ResponseWriter, r *http.Request) {
+ // GET adoption and remove from list stored in memory
+ vars := mux.Vars(r)
+ id, err := strconv.Atoi(vars["id"])
+
+ if err != nil {
+ w.Write([]byte("Adoption ID not valid"))
+ return
+ }
+
+ adoption, index := ar.GetAdoptionByID(id)
+ if adoption != nil {
+ ar.RemoveAdoptionByID(index)
+ fmt.Fprintf(w, "The adoption with ID %v has been deleted successfully", id)
+ } else {
+ fmt.Fprintf(w, "The adoption with ID %v was not found", id)
+ }
+}
diff --git a/adoption_handlers.go b/adoption_handlers.go
deleted file mode 100644
index 7714ff9..0000000
--- a/adoption_handlers.go
+++ /dev/null
@@ -1,101 +0,0 @@
-package main
-
-import (
- "encoding/json"
- "fmt"
- "net/http"
- "strconv"
-
- "github.com/gorilla/mux"
-)
-
-type Adoption struct {
- ID int `json:"id"`
- Adopter *Adopter `json:"adopter"`
- Adoptee *Adoptee `json:"adoptee"`
- Date string `json:"date"`
-}
-
-var adoptions []*Adoption
-var adoptionSeq = intSeq()
-
-var createAdoptionHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- vars := mux.Vars(r)
- adopterID, err := strconv.Atoi(vars["adopter_id"])
- if err != nil {
- fmt.Println(fmt.Errorf("Error: %v", err))
- w.WriteHeader(http.StatusInternalServerError)
- return
- }
- adopteeID, err := strconv.Atoi(vars["adoptee_id"])
- if err != nil {
- fmt.Println(fmt.Errorf("Error: %v", err))
- w.WriteHeader(http.StatusInternalServerError)
- return
- }
-
- adopter, _ := getAdopterByID(adopterID)
- adoptee, _ := getAdopteeByID(adopteeID)
- if adopter == nil || adoptee == nil {
- w.Write([]byte("Adopter ID and/or Adoptee ID not found"))
- return
- }
- adoption := Adoption{}
- adoption.ID = adoptionSeq()
- adoption.Adopter = adopter
- adoption.Adoptee = adoptee
- adoptions = append(adoptions, &adoption)
-
- payload, _ := json.Marshal(adoptions)
- w.Write([]byte(payload))
-
-})
-
-var getAdoptionHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- vars := mux.Vars(r)
- id, err := strconv.Atoi(vars["id"])
-
- if err != nil {
- w.Write([]byte("Adoption ID not valid"))
- return
- }
-
- w.Header().Set("Content-Type", "application/json")
- adoption, _ := getAdoptionByID(id)
- if adoption != nil {
- payload, _ := json.Marshal(adoption)
- w.Write([]byte(payload))
- } else {
- w.Write([]byte("Adoption Not Found"))
- }
-
-})
-
-var getAdoptionsHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- adoptionListBytes, err := json.Marshal(adoptions)
- if err != nil {
- fmt.Println(fmt.Errorf("Error: %v", err))
- w.WriteHeader(http.StatusInternalServerError)
- return
- }
- w.Write(adoptionListBytes)
-})
-
-var deleteAdoptionHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- // GET adopter and remove from list stored in memory
- vars := mux.Vars(r)
- id, err := strconv.Atoi(vars["id"])
-
- if err != nil {
- w.Write([]byte("Adoption ID not valid"))
- return
- }
-
- adoption, index := getAdoptionByID(id)
- if adoption != nil {
- removeAdoptionByID(index)
- w.Write([]byte("Adoption with ID " + string(index) + " removed"))
- } else {
- w.Write([]byte("Adoption Not Found"))
- }
-})
diff --git a/animal-rescue b/animal-rescue
index eff43f8..ec92457 100755
Binary files a/animal-rescue and b/animal-rescue differ
diff --git a/animal_rescue.go b/animal_rescue.go
new file mode 100644
index 0000000..4d61e05
--- /dev/null
+++ b/animal_rescue.go
@@ -0,0 +1,128 @@
+package main
+
+// AnimalRescue represents an organization
+// consisting of Adopter and Adoptee Relationships
+type AnimalRescue struct {
+ Adopters []*Adopter
+ Adoptees []*Adoptee
+ Adoptions []*Adoption
+ PetPreferences []*PetPreference
+
+ AdopterSeq func() int
+ AdopteeSeq func() int
+ AdoptionSeq func() int
+ PetPreferenceSeq func() int
+}
+
+func (ar *AnimalRescue) init() {
+ adopters := make([]*Adopter, 0)
+ adoptees := make([]*Adoptee, 0)
+ adoptions := make([]*Adoption, 0)
+ petPreferences := make([]*PetPreference, 0)
+ adopterSeq := intSeq()
+ adopteeSeq := intSeq()
+ adoptionSeq := intSeq()
+ petPrefSeq := intSeq()
+
+ ar.Adopters = adopters
+ ar.Adoptees = adoptees
+ ar.Adoptions = adoptions
+ ar.PetPreferences = petPreferences
+ ar.AdopterSeq = adopterSeq
+ ar.AdopteeSeq = adopteeSeq
+ ar.AdoptionSeq = adoptionSeq
+ ar.PetPreferenceSeq = petPrefSeq
+
+}
+
+// Adopter-related Helpers
+
+func (ar *AnimalRescue) GetAdopterByID(id int) (*Adopter, int) {
+ var adopter *Adopter
+ var index int
+ for i, a := range ar.Adopters {
+ if a.ID == id {
+ adopter = a
+ index = i
+ }
+ }
+ return adopter, index
+}
+
+func (ar *AnimalRescue) RemoveAdopterByID(index int) {
+ var emptyAdopter *Adopter
+ ar.Adopters[index] = ar.Adopters[len(ar.Adopters)-1]
+ ar.Adopters[len(ar.Adopters)-1] = emptyAdopter
+ ar.Adopters = ar.Adopters[:len(ar.Adopters)-1]
+}
+
+// Adoptee-related Helpers
+
+func (ar *AnimalRescue) GetAdopteeByID(id int) (*Adoptee, int) {
+ var adoptee *Adoptee
+ var index int
+ for i, a := range ar.Adoptees {
+ if a.ID == id {
+ adoptee = a
+ index = i
+ }
+ }
+ return adoptee, index
+}
+
+func (ar *AnimalRescue) RemoveAdopteeByID(index int) {
+ var emptyAdoptee *Adoptee
+ ar.Adoptees[index] = ar.Adoptees[len(ar.Adoptees)-1]
+ ar.Adoptees[len(ar.Adoptees)-1] = emptyAdoptee
+ ar.Adoptees = ar.Adoptees[:len(ar.Adoptees)-1]
+}
+
+// Adoption-related Helpers
+
+func (ar *AnimalRescue) GetAdoptionByID(id int) (*Adoption, int) {
+ var adoption *Adoption
+ var index int
+ for i, a := range ar.Adoptions {
+ if a.ID == id {
+ adoption = a
+ index = i
+ }
+ }
+ return adoption, index
+}
+
+func (ar *AnimalRescue) RemoveAdoptionByID(index int) {
+ var emptyAdoption *Adoption
+ ar.Adoptions[index] = ar.Adoptions[len(ar.Adoptions)-1]
+ ar.Adoptions[len(ar.Adoptions)-1] = emptyAdoption
+ ar.Adoptions = ar.Adoptions[:len(ar.Adoptions)-1]
+}
+
+// Pet Preference-related Helpers
+
+func (ar *AnimalRescue) GetPetPreferenceByID(id int) (*PetPreference, int) {
+ var petPreference *PetPreference
+ var index int
+ for i, p := range ar.PetPreferences {
+ if p.ID == id {
+ petPreference = p
+ index = i
+ }
+ }
+ return petPreference, index
+}
+
+func (ar *AnimalRescue) RemovePetPreferenceByID(index int) {
+ var emptyPetPreference *PetPreference
+ ar.PetPreferences[index] = ar.PetPreferences[len(ar.PetPreferences)-1]
+ ar.PetPreferences[len(ar.PetPreferences)-1] = emptyPetPreference
+ ar.PetPreferences = ar.PetPreferences[:len(ar.PetPreferences)-1]
+}
+
+func intSeq() func() int {
+ i := 0
+ return func() int {
+ i++
+ return i
+ }
+}
diff --git a/helpers.go b/helpers.go
deleted file mode 100644
index bacc767..0000000
--- a/helpers.go
+++ /dev/null
@@ -1,100 +0,0 @@
-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 bcb2225..999b12e 100644
--- a/main.go
+++ b/main.go
@@ -8,35 +8,38 @@ import (
"github.com/gorilla/mux"
)
+var animalRescue *AnimalRescue
+
func main() {
+ animalRescue = new(AnimalRescue)
+ animalRescue.init()
r := mux.NewRouter()
r.Handle("/", http.FileServer(http.Dir("./views/")))
- r.PathPrefix("/static/").Handler(http.StripPrefix("/static/", http.FileServer(http.Dir("./static/"))))
- // Defining the API
+ // Defining the API Routes
r.Handle("/status", statusHandler).Methods("GET")
- r.Handle("/adopter", createAdopterHandler).Methods("POST")
- r.Handle("/adopters", getAdoptersHandler).Methods("GET")
- r.Handle("/adopter/{id}", getAdopterHandler).Methods("GET")
- r.Handle("/adopter/{id}", updateAdopterHandler).Methods("PATCH")
- r.Handle("/adopter/{id}", deleteAdopterHandler).Methods("DELETE")
-
- 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("PATCH")
- r.Handle("/adoptees/{id}/delete", deleteAdopteeHandler).Methods("DELETE")
-
- r.Handle("/petpref", createPetPreferenceHandler).Methods("POST")
- r.Handle("/petprefs", getPetPreferencesHandler).Methods("GET")
- r.Handle("/petpref/{id}/update", updatePetPrefenceHandler).Methods("PATCH")
- r.Handle("/petpref/{id}", deletePetPreferenceHandler).Methods("DELETE")
-
- 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")
+ r.HandleFunc("/adopter", animalRescue.CreateAdopter).Methods("POST")
+ r.HandleFunc("/adopters", animalRescue.GetAdopters).Methods("GET")
+ r.HandleFunc("/adopter/{id}", animalRescue.GetAdopter).Methods("GET")
+ r.HandleFunc("/adopter/{id}", animalRescue.UpdateAdopter).Methods("PATCH")
+ r.HandleFunc("/adopter/{id}", animalRescue.DeleteAdopter).Methods("DELETE")
+
+ r.HandleFunc("/adoptee", animalRescue.CreateAdoptee).Methods("POST")
+ r.HandleFunc("/adoptees", animalRescue.GetAdoptees).Methods("GET")
+ r.HandleFunc("/adoptee/{id}", animalRescue.GetAdoptee).Methods("GET")
+ r.HandleFunc("/adoptee/{id}", animalRescue.UpdateAdoptee).Methods("PATCH")
+ r.HandleFunc("/adoptees/{id}", animalRescue.DeleteAdoptee).Methods("DELETE")
+
+ r.HandleFunc("/petpref", animalRescue.CreatePetPreference).Methods("POST")
+ r.HandleFunc("/petprefs", animalRescue.GetPetPreferences).Methods("GET")
+ r.HandleFunc("/petpref/{id}", animalRescue.UpdatePetPreference).Methods("PATCH")
+ r.HandleFunc("/petpref/{id}", animalRescue.DeletePetPreference).Methods("DELETE")
+
+ r.HandleFunc("/adoption", animalRescue.CreateAdoption).Methods("POST")
+ r.HandleFunc("/adoptions", animalRescue.GetAdoptions).Methods("GET")
+ r.HandleFunc("/adoption/{id}", animalRescue.GetAdoption).Methods("GET")
+ r.HandleFunc("/adoption/{id}", animalRescue.DeleteAdoption).Methods("DELETE")
http.ListenAndServe(":3000", handlers.LoggingHandler(os.Stdout, r))
diff --git a/pet_preference.go b/pet_preference.go
new file mode 100644
index 0000000..5d14a09
--- /dev/null
+++ b/pet_preference.go
@@ -0,0 +1,83 @@
+package main
+
+import (
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "strconv"
+
+ "github.com/gorilla/mux"
+)
+
+type PetPreference struct {
+ ID int `json:"id"`
+ Breed string `json:"breed"`
+ Age string `json:"age"`
+ Gender string `json:"gender"`
+}
+
+func (ar *AnimalRescue) CreatePetPreference(w http.ResponseWriter, r *http.Request) {
+ decoder := json.NewDecoder(r.Body)
+ petPreference := new(PetPreference)
+ err := decoder.Decode(petPreference)
+ if err != nil {
+ fmt.Println(fmt.Errorf("Error: %v", err))
+ w.WriteHeader(http.StatusInternalServerError)
+ return
+ }
+ petPreference.ID = ar.PetPreferenceSeq()
+ ar.PetPreferences = append(ar.PetPreferences, petPreference)
+
+ w.WriteHeader(http.StatusCreated)
+ json.NewEncoder(w).Encode(petPreference)
+}
+
+func (ar *AnimalRescue) GetPetPreferences(w http.ResponseWriter, r *http.Request) {
+ json.NewEncoder(w).Encode(ar.PetPreferences)
+}
+
+func (ar *AnimalRescue) UpdatePetPreference(w http.ResponseWriter, r *http.Request) {
+ // GET pet_preference and update fields
+ vars := mux.Vars(r)
+ id, err := strconv.Atoi(vars["id"])
+
+ if err != nil {
+ w.Write([]byte("Pet Preference ID not valid"))
+ return
+ }
+ petPreference, _ := ar.GetPetPreferenceByID(id)
+
+ if petPreference == nil {
+ w.Write([]byte(fmt.Sprintf("Pet Preference with ID %d not found", id)))
+ return
+ }
+
+ decoder := json.NewDecoder(r.Body)
+ updatedPetPreference := new(PetPreference)
+ err = decoder.Decode(updatedPetPreference)
+
+ if err == nil {
+ updatedPetPreference.ID = id
+ *petPreference = *updatedPetPreference
+ json.NewEncoder(w).Encode(petPreference)
+ }
+}
+
+func (ar *AnimalRescue) DeletePetPreference(w http.ResponseWriter, r *http.Request) {
+ // GET pet_preference and remove from list stored in memory
+ vars := mux.Vars(r)
+ id, err := strconv.Atoi(vars["id"])
+
+ if err != nil {
+ w.Write([]byte("Pet Preference ID not valid"))
+ return
+ }
+
+ petPreference, index := ar.GetPetPreferenceByID(id)
+ if petPreference != nil {
+ ar.RemovePetPreferenceByID(index)
+ fmt.Fprintf(w, "The pet_preference with ID %v has been deleted successfully", id)
+ } else {
+ fmt.Fprintf(w, "The pet_preference with ID %v was not found", id)
+ }
+}
diff --git a/petpreference_handlers.go b/petpreference_handlers.go
deleted file mode 100644
index eb4040d..0000000
--- a/petpreference_handlers.go
+++ /dev/null
@@ -1,97 +0,0 @@
-package main
-
-import (
- "encoding/json"
- "fmt"
- "net/http"
- "reflect"
- "strconv"
-
- "github.com/gorilla/mux"
-)
-
-type PetPreference struct {
- ID int `json:"id"`
- Breed string `json:"breed"`
- Age string `json:"age"`
- Gender string `json:"gender"`
-}
-
-var petPreferences []*PetPreference
-var petPreferenceSeq = intSeq()
-
-var createPetPreferenceHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- petPreference := PetPreference{}
- petPreference.ID = petPreferenceSeq()
- requestQuery := r.URL.Query()
-
- for key := range requestQuery {
- value := requestQuery.Get(key)
- switch key {
- case "breed":
- petPreference.Breed = value
- case "age":
- petPreference.Age = value
- case "gender":
- petPreference.Gender = value
- }
- }
- 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(petPreferences)
- if err != nil {
- fmt.Println(fmt.Errorf("Error: %v", err))
- w.WriteHeader(http.StatusInternalServerError)
- return
- }
- w.Write(petPrefsListBytes)
-})
-
-var updatePetPrefenceHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- // GET PetPreference and update fields
- vars := mux.Vars(r)
- id, err := strconv.Atoi(vars["id"])
-
- if err != nil {
- w.Write([]byte("Pet Preference ID not valid"))
- return
- }
-
- w.Header().Set("Content-Type", "application/json")
-
- petPreference, _ := getPetPreferenceByID(id)
- if petPreference != nil {
- requestQuery := r.URL.Query()
- for key := range requestQuery {
- value := requestQuery.Get(key)
- reflect.ValueOf(petPreference).Elem().FieldByName(key).SetString(value)
- }
- payload, _ := json.Marshal(petPreference)
- w.Write([]byte(payload))
- } else {
- w.Write([]byte("Pet Preference Not Found"))
- }
-})
-
-var deletePetPreferenceHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- // GET PetPreference and remove from list stored in memory
- vars := mux.Vars(r)
- id, err := strconv.Atoi(vars["id"])
-
- if err != nil {
- w.Write([]byte("Pet Preference ID not valid"))
- return
- }
-
- petPreference, index := getPetPreferenceByID(id)
- if petPreference != nil {
- removePetPreferenceByID(index)
- w.Write([]byte("Pet Preference with ID " + string(index) + " removed"))
- } else {
- w.Write([]byte("Pet Preference Not Found"))
- }
-})
diff --git a/static/.babelrc b/static/.babelrc
deleted file mode 100644
index e90ca10..0000000
--- a/static/.babelrc
+++ /dev/null
@@ -1 +0,0 @@
-{"presets":["react"]}
\ No newline at end of file
diff --git a/static/js/app.jsx b/static/js/app.jsx
deleted file mode 100644
index 50d3f38..0000000
--- a/static/js/app.jsx
+++ /dev/null
@@ -1,166 +0,0 @@
-var App = React.createClass({
- componentWillMount: function() {
- this.setState();
- },
- setState: function(){
- var idToken = localStorage.getItem('id_token');
- if(idToken){
- this.loggedIn = true;
- } else {
- localStorage.setItem('id_token', 'bearer secret1')
- this.loggedIn = false;
- }
- },
- render: function() {
-
- if (this.loggedIn) {
- return (
Below you'll find the latest adopters and adoptees in the registry. Please complete the form to continue adding to the registry.
-