-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
168 lines (122 loc) · 3.33 KB
/
main.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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
package main
import (
"context"
"encoding/json"
"log"
"net/http"
"github.com/linux-devil/go_mongo/helper"
"github.com/linux-devil/go_mongo/models"
"github.com/gorilla/mux"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
)
//Connection mongoDB with helper class
var collection = helper.ConnectDB()
func getBooks(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
//book array
var books []models.Book
//bson.M{} , empty filter as we want all the data
cur, err := collection.Find(context.TODO(), bson.M{})
if err != nil {
helper.GetError(err, w)
return
}
defer cur.Close(context.TODO())
for cur.Next(context.TODO()) {
var book models.Book
err := cur.Decode(&book)
if err != nil {
log.Fatal(err)
}
books = append(books, book)
}
if err := cur.Err(); err != nil {
log.Fatal(err)
}
json.NewEncoder(w).Encode(books)
}
func getBook(w http.ResponseWriter, r *http.Request) {
//set header
w.Header().Set("Content-Type", "application/json")
var book models.Book
//get params with mux
var params = mux.Vars(r)
id, _ := primitive.ObjectIDFromHex(params["id"])
//create filter
filter := bson.M{"_id": id}
err := collection.FindOne(context.TODO(), filter).Decode(&book)
if err != nil {
helper.GetError(err, w)
return
}
json.NewEncoder(w).Encode(book)
}
func updateBook(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
var params = mux.Vars(r)
id, _ := primitive.ObjectIDFromHex(params["id"])
var book models.Book
filter := bson.M{"_id": id}
// read update model from body request
_ = json.NewDecoder(r.Body).Decode(&book)
// prepare update model
update := bson.D{
{"$set", bson.D{
{"isbn", book.Isbin},
{"title", book.Title},
{"author", bson.D{
{"firstname", book.Author.FirstName},
{"lastname", book.Author.LastName},
}},
}},
}
err := collection.FindOneAndUpdate(context.TODO(), filter, update).Decode(&book)
if err != nil {
helper.GetError(err, w)
return
}
book.ID = id
json.NewEncoder(w).Encode(book)
}
func deleteBook(w http.ResponseWriter, r *http.Request) {
//Set header
w.Header().Set("Content-Type", "application/json")
//get params
var params = mux.Vars(r)
//string to primitive Object Id
id, err := primitive.ObjectIDFromHex(params["id"])
// filter
filter := bson.M{"_id": id}
deleteResult, err := collection.DeleteOne(context.TODO(), filter)
if err != nil {
helper.GetError(err, w)
return
}
json.NewEncoder(w).Encode(deleteResult)
}
func createBook(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
var book models.Book
//decode body request params
_ = json.NewDecoder(r.Body).Decode(&book)
//insert new book model
result, err := collection.InsertOne(context.TODO(), book)
if err != nil {
helper.GetError(err, w)
return
}
json.NewEncoder(w).Encode(result)
}
func main() {
//Init Router
r := mux.NewRouter()
//arrange our route
r.HandleFunc("/api/books", getBooks).Methods("GET")
r.HandleFunc("/api/books/{id}", getBook).Methods("GET")
r.HandleFunc("/api/books", createBook).Methods("POST")
r.HandleFunc("/api/books/{id}", getBooks).Methods("PUT")
r.HandleFunc("/api/books/{id}", deleteBook).Methods("DELETE")
// set port address
log.Fatal(http.ListenAndServe(":8000", r))
}