forked from s1s1ty/go-mysql-crud
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpost.go
99 lines (78 loc) · 2.55 KB
/
post.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
package handler
import (
"encoding/json"
"fmt"
"net/http"
"strconv"
"github.com/go-chi/chi"
"github.com/s1s1ty/go-mysql-crud/driver"
models "github.com/s1s1ty/go-mysql-crud/models"
repository "github.com/s1s1ty/go-mysql-crud/repository"
post "github.com/s1s1ty/go-mysql-crud/repository/post"
)
// NewPostHandler ...
func NewPostHandler(db *driver.DB) *Post {
return &Post{
repo: post.NewSQLPostRepo(db.SQL),
}
}
// Post ...
type Post struct {
repo repository.PostRepo
}
// Fetch all post data
func (p *Post) Fetch(w http.ResponseWriter, r *http.Request) {
payload, _ := p.repo.Fetch(r.Context(), 5)
respondwithJSON(w, http.StatusOK, payload)
}
// Create a new post
func (p *Post) Create(w http.ResponseWriter, r *http.Request) {
post := models.Post{}
json.NewDecoder(r.Body).Decode(&post)
newID, err := p.repo.Create(r.Context(), &post)
fmt.Println(newID)
if err != nil {
respondWithError(w, http.StatusInternalServerError, "Server Error")
}
respondwithJSON(w, http.StatusCreated, map[string]string{"message": "Successfully Created"})
}
// Update a post by id
func (p *Post) Update(w http.ResponseWriter, r *http.Request) {
id, _ := strconv.Atoi(chi.URLParam(r, "id"))
data := models.Post{ID: int64(id)}
json.NewDecoder(r.Body).Decode(&data)
payload, err := p.repo.Update(r.Context(), &data)
if err != nil {
respondWithError(w, http.StatusInternalServerError, "Server Error")
}
respondwithJSON(w, http.StatusOK, payload)
}
// GetByID returns a post details
func (p *Post) GetByID(w http.ResponseWriter, r *http.Request) {
id, _ := strconv.Atoi(chi.URLParam(r, "id"))
payload, err := p.repo.GetByID(r.Context(), int64(id))
if err != nil {
respondWithError(w, http.StatusNoContent, "Content not found")
}
respondwithJSON(w, http.StatusOK, payload)
}
// Delete a post
func (p *Post) Delete(w http.ResponseWriter, r *http.Request) {
id, _ := strconv.Atoi(chi.URLParam(r, "id"))
_, err := p.repo.Delete(r.Context(), int64(id))
if err != nil {
respondWithError(w, http.StatusInternalServerError, "Server Error")
}
respondwithJSON(w, http.StatusMovedPermanently, map[string]string{"message": "Delete Successfully"})
}
// respondwithJSON write json response format
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)
}
// respondwithError return error message
func respondWithError(w http.ResponseWriter, code int, msg string) {
respondwithJSON(w, code, map[string]string{"message": msg})
}