-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathadoption.go
76 lines (63 loc) · 1.73 KB
/
adoption.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
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[adoption.ID] = 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.Adoptions[id]
if adoption != nil {
json.NewEncoder(w).Encode(adoption)
}
}
func (ar *AnimalRescue) GetAdoptions(w http.ResponseWriter, r *http.Request) {
adoptions := make([]*Adoption, 0, len(ar.Adoptions))
for _, adoption := range ar.Adoptions {
adoptions = append(adoptions, adoption)
}
json.NewEncoder(w).Encode(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 := ar.Adoptions[id]
if adoption != nil {
delete(ar.Adoptions, id)
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)
}
}