-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
103 lines (72 loc) · 2.32 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
package main
import (
"context"
"encoding/json"
"log"
"net/http"
"github.com/gorilla/mux"
"github.com/mvmdev/appointy/helper"
"github.com/mvmdev/appointy/models"
"github.com/mvmdev/appointy/new_helper"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
)
var collectionUser = helper.ConnectDB()
var collectionContact = new_helper.ConnectDB()
func getUser(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
var user models.User
var params = mux.Vars(r)
id, _ := primitive.ObjectIDFromHex(params["id"])
filter := bson.M{"_id": id}
err := collectionUser.FindOne(context.TODO(), filter).Decode(&user)
if err != nil {
helper.GetError(err, w)
return
}
json.NewEncoder(w).Encode(user)
}
func createUser(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
var user models.User
_ = json.NewDecoder(r.Body).Decode(&user)
result, err := collectionUser.InsertOne(context.TODO(), user)
if err != nil {
helper.GetError(err, w)
return
}
json.NewEncoder(w).Encode(result)
}
func createContact(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
var contact models.Contact
_ = json.NewDecoder(r.Body).Decode(&contact)
result, err := collectionContact.InsertOne(context.TODO(), contact)
if err != nil {
new_helper.GetError(err, w)
return
}
json.NewEncoder(w).Encode(result)
}
func getContact(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
var contact models.Contact
var params = mux.Vars(r)
id, _ := primitive.ObjectIDFromHex(params["id"])
filter := bson.M{"_id": id}
err := collectionContact.FindOne(context.TODO(), filter).Decode(&contact)
if err != nil {
new_helper.GetError(err, w)
return
}
json.NewEncoder(w).Encode(contact)
}
func main() {
route := mux.NewRouter()
route.HandleFunc("/users", createUser).Methods("POST")
route.HandleFunc("/users/{id}", getUser).Methods("GET")
route.HandleFunc("/contacts", createContact).Methods("POST")
route.HandleFunc("/contacts/{id}", getContact).Methods("GET")
config := helper.GetConfiguration()
log.Fatal(http.ListenAndServe(config.Port, route))
}