-
Notifications
You must be signed in to change notification settings - Fork 0
/
note.go
100 lines (77 loc) · 2.57 KB
/
note.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
package handler
import (
"encoding/json"
"net/http"
"strconv"
"github.com/go-chi/chi"
"github.com/murawakimitsuhiro/go-simple-RESTful-api/driver"
"github.com/murawakimitsuhiro/go-simple-RESTful-api/models"
"github.com/murawakimitsuhiro/go-simple-RESTful-api/repository"
"github.com/murawakimitsuhiro/go-simple-RESTful-api/repository/note"
)
func NewNoteHandler(db *driver.DB) *Note {
return &Note{
repo: note.NewGormRepo(db.DB),
}
}
type Note struct {
repo repository.NoteRepo
}
func (n *Note) Fetch(w http.ResponseWriter, r *http.Request) {
payload, _ := n.repo.Fetch(r.Context(), 100)
respondWithJSON(w, http.StatusOK, payload)
}
func (n *Note) Create(w http.ResponseWriter, r *http.Request) {
note := models.Note{}
if err := json.NewDecoder(r.Body).Decode(¬e); err != nil {
respondWithError(w, http.StatusBadRequest, "Request Error")
return
}
if _, err := n.repo.Create(r.Context(), ¬e); err != nil {
respondWithError(w, http.StatusInternalServerError, "Server Error")
return
}
respondWithJSON(w, http.StatusCreated, map[string]string{"message": "Successfully Created"})
}
func (n *Note) Update(w http.ResponseWriter, r *http.Request) {
id, _ := strconv.Atoi(chi.URLParam(r, "id"))
data := models.Note{}
data.ID = uint(id)
if err := json.NewDecoder(r.Body).Decode(&data); err != nil {
respondWithError(w, http.StatusBadRequest, "Request Error")
return
}
payload, err := n.repo.Update(r.Context(), &data)
if err != nil {
respondWithError(w, http.StatusInternalServerError, "Server Error")
return
}
respondWithJSON(w, http.StatusOK, payload)
}
func (n *Note) GetByID(w http.ResponseWriter, r *http.Request) {
id, _ := strconv.Atoi(chi.URLParam(r, "id"))
payload, err := n.repo.GetByID(r.Context(), uint(id))
if err != nil {
respondWithError(w, http.StatusNoContent, "Content not found")
return
}
respondWithJSON(w, http.StatusOK, payload)
}
func (n *Note) Delete(w http.ResponseWriter, r *http.Request) {
id, _ := strconv.Atoi(chi.URLParam(r, "id"))
_, err := n.repo.Delete(r.Context(), uint(id))
if err != nil {
respondWithError(w, http.StatusInternalServerError, "Server Error")
return
}
respondWithJSON(w, http.StatusMovedPermanently, map[string]string{"message": "Delete Successfully"})
}
func respondWithJSON(w http.ResponseWriter, code int, payload interface{}) {
response, _ := json.Marshal(payload)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(code)
w.Write(response)
}
func respondWithError(w http.ResponseWriter, code int, msg string) {
respondWithJSON(w, code, map[string]string{"message": msg})
}