-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathmain.go
179 lines (131 loc) · 3.99 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
169
170
171
172
173
174
175
176
177
178
179
package main
import (
"context"
"encoding/json"
"log"
"net/http"
"github.com/faygun/go-rest-api/helper"
"github.com/faygun/go-rest-api/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")
// we created Book array
var books []models.Book
// bson.M{}, we passed empty filter. So we want to get all data.
cur, err := collection.Find(context.TODO(), bson.M{})
if err != nil {
helper.GetError(err, w)
return
}
// Close the cursor once finished
/*A defer statement defers the execution of a function until the surrounding function returns.
simply, run cur.Close() process but after cur.Next() finished.*/
defer cur.Close(context.TODO())
for cur.Next(context.TODO()) {
// create a value into which the single document can be decoded
var book models.Book
// & character returns the memory address of the following variable.
err := cur.Decode(&book) // decode similar to deserialize process.
if err != nil {
log.Fatal(err)
}
// add item our array
books = append(books, book)
}
if err := cur.Err(); err != nil {
log.Fatal(err)
}
json.NewEncoder(w).Encode(books) // encode similar to serialize process.
}
func getBook(w http.ResponseWriter, r *http.Request) {
// set header.
w.Header().Set("Content-Type", "application/json")
var book models.Book
// we get params with mux.
var params = mux.Vars(r)
// string to primitive.ObjectID
id, _ := primitive.ObjectIDFromHex(params["id"])
// We create filter. If it is unnecessary to sort data for you, you can use bson.M{}
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 createBook(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
var book models.Book
// we decode our body request params
_ = json.NewDecoder(r.Body).Decode(&book)
// insert our book model.
result, err := collection.InsertOne(context.TODO(), book)
if err != nil {
helper.GetError(err, w)
return
}
json.NewEncoder(w).Encode(result)
}
func updateBook(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
var params = mux.Vars(r)
//Get id from parameters
id, _ := primitive.ObjectIDFromHex(params["id"])
var book models.Book
// Create filter
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.Isbn},
{"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 primitve.ObjectID
id, err := primitive.ObjectIDFromHex(params["id"])
// prepare 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)
}
// var client *mongo.Client
func main() {
//Init Router
r := mux.NewRouter()
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}", updateBook).Methods("PUT")
r.HandleFunc("/api/books/{id}", deleteBook).Methods("DELETE")
config := helper.GetConfiguration()
log.Fatal(http.ListenAndServe(config.Port, r))
}