-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
240 lines (196 loc) · 6.28 KB
/
main.go
File metadata and controls
240 lines (196 loc) · 6.28 KB
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
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
package main
import (
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"log"
"net/http"
"strconv"
"strings"
"time"
"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"
)
const (
Database = "Instagram" //Database Name
UserCollection = "Accounts" // User Collection
PostsCollection = "Posts" // Post Collection
)
type User struct {
Id primitive.ObjectID `json:"Id,omitempty" bson:"_id,omitempty"`
Name string `json:"Name" bson:"Name"`
Email string `json:"Email" bson:"Email"`
Password string `json:"Password" bson:"Password"`
}
type Post struct {
Id primitive.ObjectID `json:"Id,omitempty" bson:"_id,omitempty"`
Uid primitive.ObjectID `json:"UId,omitempty" bson:"Uid,omitempty"`
Caption string `json:"Caption,omitempty"`
Image_URL string `json:"Image_URL,omitempty"`
Posted_Timestamp primitive.Timestamp `json:"Timestamp,omitempty"`
}
var client *mongo.Client
func reportError(w http.ResponseWriter, err error) {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(`{"message":"` + err.Error() + `"}`))
}
func GetUser(response http.ResponseWriter, request *http.Request) {
response.Header().Set("Content-Type", "application/json")
collection := client.Database(Database).Collection(UserCollection)
ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
uid := getId(request.URL.Path)
id, err := primitive.ObjectIDFromHex(uid)
if err != nil {
reportError(response, err)
}
var user User
FindId := bson.M{"_id": id}
err = collection.FindOne(ctx, FindId).Decode(&user)
if err != nil {
reportError(response, errors.New("Invalid!,User does not exist"))
return
}
json.NewEncoder(response).Encode(user)
}
func PostUser(response http.ResponseWriter, request *http.Request) {
response.Header().Set("Content-Type", "application/json")
collection := client.Database(Database).Collection(UserCollection)
ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
var user User
err := json.NewDecoder(request.Body).Decode(&user)
if err != nil {
reportError(response, err)
return
}
//if User already exists with email,throw error
FindEmail := bson.M{"Email": user.Email}
Cursor, err := collection.Find(ctx, FindEmail)
if err != nil {
reportError(response, err)
}
var filteredUser []bson.M
if err = Cursor.All(ctx, &filteredUser); err != nil {
reportError(response, err)
return
}
defer Cursor.Close(ctx)
if len(filteredUser) != 0 {
var alreadyExistsError = errors.New("User Already Exists")
reportError(response, alreadyExistsError)
return
}
hash := sha256.New()
hash.Write([]byte(user.Password))
user.Password = hex.EncodeToString(hash.Sum(nil))
result, _ := collection.InsertOne(ctx, user)
json.NewEncoder(response).Encode(result)
}
func GetPost(response http.ResponseWriter, request *http.Request) {
response.Header().Set("Content-Type", "application/json")
PC := client.Database(Database).Collection(PostsCollection)
ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
pid := getId(request.URL.Path)
id, err := primitive.ObjectIDFromHex(pid)
if err != nil {
reportError(response, err)
}
var post Post
FindId := bson.M{"_id": id}
err = PC.FindOne(ctx, FindId).Decode(&post)
if err != nil {
reportError(response, errors.New("Post Doesnt Exists"))
return
}
json.NewEncoder(response).Encode(post)
}
func PostPost(response http.ResponseWriter, request *http.Request) {
UC := client.Database(Database).Collection(UserCollection)
PC := client.Database(Database).Collection(PostsCollection)
ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
var post Post
err := json.NewDecoder(request.Body).Decode(&post)
if err != nil {
reportError(response, err)
return
}
var user User
FindId := bson.M{"_id": post.Uid}
err = UC.FindOne(ctx, FindId).Decode(&user)
if err != nil {
reportError(response, errors.New("User Doesnt Exists"))
return
}
post.Posted_Timestamp = primitive.Timestamp{T: uint32(time.Now().Unix())}
result, err := PC.InsertOne(ctx, post)
if err != nil {
reportError(response, err)
return
}
json.NewEncoder(response).Encode(result)
}
func GetUserPost(response http.ResponseWriter, request *http.Request) {
request.ParseForm()
var limit int64 = 10
var skip int64 = 0
if len(request.Form) > 0 {
for k, v := range request.Form {
if k == "skip" {
skip, _ = strconv.ParseInt(v[0], 10, 64)
}
if k == "limit" {
limit, _ = strconv.ParseInt(v[0], 10, 64)
}
}
}
multiOptions := options.Find().SetLimit(limit).SetSkip(skip)
log.Println(request.URL)
response.Header().Set("Content-Type", "application/json")
collection := client.Database(Database).Collection(PostsCollection)
ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
if request.Method != "GET" {
response.WriteHeader(http.StatusNotFound)
return
}
uid := getId(request.URL.Path)
id, err := primitive.ObjectIDFromHex(uid)
if err != nil {
reportError(response, err)
return
}
FindPost := bson.M{"Uid": id}
Cursor, err := collection.Find(ctx, FindPost, multiOptions)
if err != nil {
reportError(response, err)
return
}
defer Cursor.Close(ctx)
var userPosts []bson.M
if err = Cursor.All(ctx, &userPosts); err != nil {
reportError(response, err)
return
}
json.NewEncoder(response).Encode(userPosts)
}
func getId(url string) string {
p := strings.Split(url, "/")
return p[len(p)-1]
}
func main() {
ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
clientOpts := options.Client().ApplyURI("mongodb://localhost:27017")
var err error
client, err = mongo.Connect(ctx, clientOpts)
if err != nil {
log.Fatalf("Error :%v", err)
}
http.HandleFunc("/users/", GetUser)
http.HandleFunc("/users", PostUser)
http.HandleFunc("/posts/", GetPost)
http.HandleFunc("/posts", PostPost)
http.HandleFunc("/posts/users/", GetUserPost)
http.ListenAndServe(":8080", nil)
}