-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinstagram.go
208 lines (189 loc) · 7.25 KB
/
instagram.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
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
package main
import (
"context"
"encoding/json"
"fmt"
"net/http"
"strconv"
"sync"
"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"
"golang.org/x/crypto/bcrypt"
)
//the Person structure to contain the various details
type Person struct {
ID primitive.ObjectID `json:"_id,omitempty" bson:"_id,omitempty"`
Name string `json:"name,omitempty" bson:"name,omitempty"`
Email string `json:"email,omitempty" bson:"email,omitempty"`
Password string `json:"password,omitempty" bson:"password,omitempty"`
}
//the Post structure to contain the various details
type Post struct {
ID primitive.ObjectID `json:"_id,omitempty" bson:"_id,omitempty"`
User primitive.ObjectID `json:"user,omitempty" bson:"user,omitempty"`
Caption string `json:"caption,omitempty" bson:"caption,omitempty"`
Image string `json:"image,omitempty" bson:"image,omitempty"`
Time string `json:"time,omitempty" bson:"time,omitempty"`
}
var client *mongo.Client
var lock sync.Mutex
//create Users Endpoint #Endpoint 1
func CreateUsersEndpoint(response http.ResponseWriter, request *http.Request) {
lock.Lock()
defer lock.Unlock()
response.Header().Add("content-type", "application/json")
var person Person
json.NewDecoder(request.Body).Decode(&person)
hash, err := bcrypt.GenerateFromPassword([]byte(person.Password), bcrypt.DefaultCost)
person.Password = string(hash)
if err != nil {
fmt.Println(err)
}
collection := client.Database("instagramAPI").Collection("users")
ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
result, _ := collection.InsertOne(ctx, person)
json.NewEncoder(response).Encode(result)
time.Sleep(1 * time.Second)
}
//Get Users Endpoint #Endpoint 2
func GetUsersEndpoint(response http.ResponseWriter, request *http.Request) {
lock.Lock()
defer lock.Unlock()
response.Header().Add("content-type", "application/json")
params := mux.Vars(request)
id, _ := primitive.ObjectIDFromHex(params["id"])
var user Person
collection := client.Database("instagramAPI").Collection("users")
ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
err := collection.FindOne(ctx, Person{ID: id}).Decode(&user)
if err != nil {
response.WriteHeader(http.StatusInternalServerError)
response.Write([]byte(`{"message": "` + err.Error() + `"}`))
return
}
json.NewEncoder(response).Encode(user)
time.Sleep(1 * time.Second)
}
//Create Post Endpoint #Endpoint 3
func CreatePostsEndpoint(response http.ResponseWriter, request *http.Request) {
lock.Lock()
defer lock.Unlock()
response.Header().Add("content-type", "application/json")
var post Post
json.NewDecoder(request.Body).Decode(&post)
post.Time = time.Now().Format("2006-01-02 15:04:05")
collection := client.Database("instagramAPI").Collection("posts")
ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
result, _ := collection.InsertOne(ctx, post)
json.NewEncoder(response).Encode(result)
time.Sleep(1 * time.Second)
}
//Get Posts Endpoint #Endpoint 4
func GetPostsEndpoint(response http.ResponseWriter, request *http.Request) {
lock.Lock()
defer lock.Unlock()
response.Header().Add("content-type", "application/json")
params := mux.Vars(request)
id, _ := primitive.ObjectIDFromHex(params["id"])
var post Post
collection := client.Database("instagramAPI").Collection("posts")
ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
err := collection.FindOne(ctx, Post{ID: id}).Decode(&post)
if err != nil {
response.WriteHeader(http.StatusInternalServerError)
response.Write([]byte(`{"message": "` + err.Error() + `"}`))
return
}
json.NewEncoder(response).Encode(post)
time.Sleep(1 * time.Second)
}
//Get all Posts of an User Endpoint #Endpoint 5
func GetAllPostsEndpoint(response http.ResponseWriter, request *http.Request) {
lock.Lock()
defer lock.Unlock()
var postt []Post
response.Header().Add("content-type", "application/json")
params := mux.Vars(request)
id, _ := primitive.ObjectIDFromHex(params["id"])
var post Post
collection := client.Database("instagramAPI").Collection("posts")
ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
cur, err := collection.Find(ctx, bson.M{"user": id})
if err != nil {
response.WriteHeader(http.StatusInternalServerError)
response.Write([]byte(`{"message": "` + err.Error() + `"}`))
return
}
for cur.Next(ctx) {
err := cur.Decode(&post)
if err != nil {
response.WriteHeader(http.StatusInternalServerError)
response.Write([]byte(`{"message": "` + err.Error() + `"}`))
return
}
postt = append(postt, post)
}
for _, item := range postt {
if item.User == id {
json.NewEncoder(response).Encode(item)
}
}
time.Sleep(1 * time.Second)
}
//Get all posts of an User based on Pagination #Endpoint Extra Pagination
func GetAllPostsEndpointPager(response http.ResponseWriter, request *http.Request) {
lock.Lock()
defer lock.Unlock()
var postt []Post
response.Header().Add("content-type", "application/json")
params := mux.Vars(request)
id, _ := primitive.ObjectIDFromHex(params["id"])
limit, _ := strconv.Atoi(params["limit"])
var post Post
collection := client.Database("instagramAPI").Collection("posts")
ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
cur, err := collection.Find(ctx, bson.M{"user": id})
if err != nil {
response.WriteHeader(http.StatusInternalServerError)
response.Write([]byte(`{"message": "` + err.Error() + `"}`))
return
}
for cur.Next(ctx) {
err := cur.Decode(&post)
if err != nil {
response.WriteHeader(http.StatusInternalServerError)
response.Write([]byte(`{"message": "` + err.Error() + `"}`))
return
}
postt = append(postt, post)
}
for _, item := range postt {
if item.User == id {
if limit > 0 {
limit--
json.NewEncoder(response).Encode(item)
}
}
}
time.Sleep(1 * time.Second)
}
//Endpoint to get all the recent
func main() {
//fmt.Println("Starting the application")
//connector function
ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
client, _ = mongo.Connect(ctx, options.Client().ApplyURI("mongodb://localhost:27017")) //connecting with mongo db client
router := mux.NewRouter()
//routers to various endpoints of the API
router.HandleFunc("/users", CreateUsersEndpoint).Methods("POST") //users Creation API
router.HandleFunc("/users/{id}", GetUsersEndpoint).Methods("GET") //users Get API
router.HandleFunc("/posts", CreatePostsEndpoint).Methods("POST") //posts Creation API
router.HandleFunc("/posts/{id}", GetPostsEndpoint).Methods("GET") //posts Get API by ID
router.HandleFunc("/posts/users/{id}&limit={limit}", GetAllPostsEndpointPager).Methods("GET") //posts Get API using Pagination
router.HandleFunc("/posts/users/{id}", GetAllPostsEndpoint).Methods("GET") //posts Get API by User ID
http.ListenAndServe(":4000", router)
}