-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.go
177 lines (144 loc) · 5.02 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
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
package main
import (
"github.com/gorilla/mux"
"log"
"net/http"
"strconv"
"time"
"encoding/json"
)
func main() {
InitRedis() // Initialize Redis
InitPostgres() // Initialize PostgreSQL
r := mux.NewRouter()
// Routes
r.HandleFunc("/user/{id}", GetUserHandler).Methods("GET")
r.HandleFunc("/users", GetPaginatedUsersHandler).Methods("GET")
r.HandleFunc("/user/{id}", UpdateUserHandler).Methods("PUT")
r.HandleFunc("/user", CreateUserHandler).Methods("POST")
r.HandleFunc("/search-users", SearchUsersHandler).Methods("GET")
// Apply rate limiter middleware
r.Use(RateLimiterMiddleware)
// Start server
srv := &http.Server{
Handler: r,
Addr: "0.0.0.0:3000",
WriteTimeout: 15 * time.Second,
ReadTimeout: 15 * time.Second,
}
log.Println("Server is running on port 3000")
log.Fatal(srv.ListenAndServe())
}
// GetUserHandler returns a single user by ID
func GetUserHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
userId := vars["id"]
log.Printf("Requested User ID: %s", userId) // Log the user ID
cacheKey := "user:" + userId
// Try to get user from Redis cache
cachedUser, _ := GetFromCache(cacheKey)
if cachedUser != "" {
log.Println("Cache hit")
w.Header().Set("Content-Type", "application/json")
w.Write([]byte(cachedUser))
return
}
// Fetch from PostgreSQL
user, err := GetUserById(userId)
if err != nil {
http.Error(w, "User not found", http.StatusNotFound)
return
}
// Set result in cache
userJson, _ := json.Marshal(user)
SetToCache(cacheKey, string(userJson))
log.Println("Cache miss, fetching from PostgreSQL")
w.Header().Set("Content-Type", "application/json")
w.Write(userJson)
}
// GetPaginatedUsersHandler fetches paginated list of users
func GetPaginatedUsersHandler(w http.ResponseWriter, r *http.Request) {
pageStr := r.URL.Query().Get("page")
limitStr := r.URL.Query().Get("limit")
page, _ := strconv.Atoi(pageStr)
limit, _ := strconv.Atoi(limitStr)
offset := (page - 1) * limit
cacheKey := "users:page:" + pageStr + ":limit:" + limitStr
// Try to get users from cache
cachedUsers, _ := GetFromCache(cacheKey)
if cachedUsers != "" {
log.Println("Cache hit")
w.Header().Set("Content-Type", "application/json")
w.Write([]byte(cachedUsers))
return
}
// Fetch users from PostgreSQL
users, err := FetchPaginatedUsers(limit, offset)
if err != nil {
http.Error(w, "Error fetching users", http.StatusInternalServerError)
return
}
usersJson, _ := json.Marshal(users)
SetToCache(cacheKey, string(usersJson))
log.Println("Cache miss, fetching from PostgreSQL")
w.Header().Set("Content-Type", "application/json")
w.Write(usersJson)
}
// UpdateUserHandler updates a user profile and invalidates cache
func UpdateUserHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
userId := vars["id"]
var user User
err := json.NewDecoder(r.Body).Decode(&user)
if err != nil {
http.Error(w, "Invalid request body", http.StatusBadRequest)
return
}
err = UpdateUser(userId, user.Name, user.Email)
if err != nil {
http.Error(w, "Error updating user", http.StatusInternalServerError)
return
}
InvalidateCache("users:page:*") // Invalidate paginated users cache
w.Header().Set("Content-Type", "application/json")
w.Write([]byte(`{"message": "User updated"}`))
}
// CreateUserHandler creates a new user
func CreateUserHandler(w http.ResponseWriter, r *http.Request) {
var user User
err := json.NewDecoder(r.Body).Decode(&user)
if err != nil {
http.Error(w, "Invalid request body", http.StatusBadRequest)
return
}
err = CreateUser(user.Name, user.Email)
if err != nil {
http.Error(w, "Error creating user", http.StatusInternalServerError)
return
}
InvalidateCache("users:page:*") // Invalidate cache after creating a new user
w.Header().Set("Content-Type", "application/json")
w.Write([]byte(`{"message": "User created"}`))
}
// SearchUsersHandler searches users by name or email
func SearchUsersHandler(w http.ResponseWriter, r *http.Request) {
query := r.URL.Query().Get("query")
cacheKey := "users:search:" + query
cachedSearch, _ := GetFromCache(cacheKey)
if cachedSearch != "" {
log.Println("Cache hit for search")
w.Header().Set("Content-Type", "application/json")
w.Write([]byte(cachedSearch))
return
}
users, err := SearchUsers(query)
if err != nil {
http.Error(w, "Error searching users", http.StatusInternalServerError)
return
}
usersJson, _ := json.Marshal(users)
SetToCache(cacheKey, string(usersJson))
log.Println("Cache miss, fetching search results from PostgreSQL")
w.Header().Set("Content-Type", "application/json")
w.Write(usersJson)
}