-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
90 lines (82 loc) · 3.08 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
package main
import (
"context"
"encoding/json"
"fmt"
"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"`
}
func CreatePersonEndpoint(response http.ResponseWriter, request *http.Request) {
response.Header().Set("content-type", "application/json")
var person Person
_ = json.NewDecoder(request.Body).Decode(&person)
collection := client.Database("sandhu-golang").Collection("people")
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
result, _ := collection.InsertOne(ctx, person)
json.NewEncoder(response).Encode(result)
}
func GetPeopleEndpoint(response http.ResponseWriter, request *http.Request) {
response.Header().Set("content-type", "application/json")
var people []Person
collection := client.Database("sandhu-golang").Collection("people")
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
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 GetPersonEndpoint(response http.ResponseWriter, request *http.Request) {
response.Header().Set("content-type", "application/json")
params := mux.Vars(request)
id, _ := primitive.ObjectIDFromHex(params["id"])
var person Person
collection := client.Database("sandhu-golang").Collection("people")
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
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 main() {
fmt.Println("Starting the application...")
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
clientOptions := options.Client().ApplyURI("mongodb+srv://Sandhu-Sahil:ssssandhu26@cluster0.yfxftsl.mongodb.net/?retryWrites=true&w=majority")
client, _ = mongo.Connect(ctx, clientOptions)
router := mux.NewRouter()
router.HandleFunc("/person", CreatePersonEndpoint).Methods("POST")
router.HandleFunc("/people", GetPeopleEndpoint).Methods("GET")
router.HandleFunc("/person/{id}", GetPersonEndpoint).Methods("GET")
http.ListenAndServe(":3000", router)
}