-
Notifications
You must be signed in to change notification settings - Fork 1
/
mongo_restproject.go
130 lines (118 loc) · 4.75 KB
/
mongo_restproject.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
package main
import (
"context"
"encoding/json"
"fmt"
"log"
"net/http"
"time"
"github.com/gorilla/mux"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
var client *mongo.Client
type Person struct {
ID primitive.ObjectID `json:"_id,omitempty" bson:"_id,omitempty"`
Firstname string `json:"firstname,omitempty" bson:"firstname,omitempty"`
Lastname string `json:"lastname,omitempty" bson:"lastname,omitempty"`
}
var people []Person
func GetPersonEndpoint(response http.ResponseWriter, request *http.Request) {
fmt.Println("Inside GetPersonEndpoint ...")
response.Header().Set("content-type", "application/json")
params := mux.Vars(request)
id, _ := primitive.ObjectIDFromHex(params["id"])
fmt.Println("GetPersonEndpoint ...")
fmt.Println(id)
var person Person
collection := client.Database("thepolyglotdeveloper").Collection("people")
ctx, _ := context.WithTimeout(context.Background(), 30*time.Second)
err := collection.FindOne(ctx, Person{ID: id}).Decode(&person)
if err != nil {
response.WriteHeader(http.StatusInternalServerError)
response.Write([]byte(`{"message":"` + err.Error() + `"}`))
return
}
json.NewEncoder(response).Encode(person)
}
func GetPeopleEndpoint(response http.ResponseWriter, req *http.Request) {
fmt.Println("Inside GetPeopleEndpoint ...")
response.Header().Set("content-type", "application/json")
var people []Person
collection := client.Database("thepolyglotdeveloper").Collection("people")
ctx, _ := context.WithTimeout(context.Background(), 30*time.Second)
cursor, err := collection.Find(ctx, bson.M{})
if err != nil {
response.WriteHeader(http.StatusInternalServerError)
response.Write([]byte(`{"message":"` + err.Error() + `"}`))
return
}
defer cursor.Close(ctx)
for cursor.Next(ctx) {
var person Person
cursor.Decode(&person)
people = append(people, person)
}
if err := cursor.Err(); err != nil {
response.WriteHeader(http.StatusInternalServerError)
response.Write([]byte(`{"message":"` + err.Error() + `"}`))
return
}
json.NewEncoder(response).Encode(people)
}
func CreatePersonEndpoint(response http.ResponseWriter, request *http.Request) {
fmt.Println("Inside CreatePersonEndpoint ...")
response.Header().Set("content-type", "application/json")
var person Person
_ = json.NewDecoder(request.Body).Decode(&person)
collection := client.Database("thepolyglotdeveloper").Collection("people")
ctx, _ := context.WithTimeout(context.Background(), 5*time.Second)
result, _ := collection.InsertOne(ctx, person)
json.NewEncoder(response).Encode(result)
}
func UpdatePersonEndpoint(response http.ResponseWriter, request *http.Request) {
fmt.Println("Inside UpdatePersonEndpoint ...")
response.Header().Set("content-type", "application/json")
var person Person
params := mux.Vars(request)
name, _ := params["firstname"]
fmt.Println(name)
_ = json.NewDecoder(request.Body).Decode(&person)
fmt.Println(person.Lastname)
collection := client.Database("thepolyglotdeveloper").Collection("people")
ctx, _ := context.WithTimeout(context.Background(), 5*time.Second)
filter := bson.D{{"firstname", name}}
update := bson.M{"$set": bson.M{"lastname": person.Lastname,},}
result, _ := collection.UpdateOne(ctx, filter, update)
json.NewEncoder(response).Encode(result)
}
func DeletePersonEndpoint(response http.ResponseWriter, request *http.Request) {
fmt.Println("Inside DeletePersonEndpoint ...")
response.Header().Set("content-type", "application/json")
var person Person
params := mux.Vars(request)
name, _ := params["firstname"]
fmt.Println(name)
_ = json.NewDecoder(request.Body).Decode(&person)
fmt.Println(person.Lastname)
collection := client.Database("thepolyglotdeveloper").Collection("people")
ctx, _ := context.WithTimeout(context.Background(), 5*time.Second)
filter := bson.D{{"firstname", name}}
result, _ := collection.DeleteOne(ctx, filter)
json.NewEncoder(response).Encode(result)
}
func main() {
fmt.Println("Starting the application...")
ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")
client, _ = mongo.Connect(ctx, clientOptions)
router := mux.NewRouter()
router.HandleFunc("/people", GetPeopleEndpoint).Methods("GET")
router.HandleFunc("/people/{id}", GetPersonEndpoint).Methods("GET")
router.HandleFunc("/person", CreatePersonEndpoint).Methods("POST")
router.HandleFunc("/people/{firstname}", UpdatePersonEndpoint).Methods("PUT")
router.HandleFunc("/people/{firstname}", DeletePersonEndpoint).Methods("DELETE")
log.Fatal(http.ListenAndServe(":8080", router))
}