Skip to content

Commit 04295c1

Browse files
authored
Only enqueue when request method is GET (#25)
1 parent 3d788da commit 04295c1

File tree

2 files changed

+9
-6
lines changed

2 files changed

+9
-6
lines changed

cmd/server/main.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -84,7 +84,7 @@ func main() {
8484
router.HandleFunc("GET /urls", handlers.GetUrls)
8585
router.HandleFunc("POST /urls", handlers.CreateUrl)
8686
router.HandleFunc("GET /health", handlers.HealthHandler)
87-
router.HandleFunc("GET /{shortCode}", handlers.Redirect)
87+
router.HandleFunc("GET, HEAD /{shortCode}", handlers.Redirect)
8888

8989
port := ":8095"
9090
// Create a new server

internal/handlers/handlers.go

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -161,16 +161,13 @@ var MAX_QUEUE_RETRY = 10
161161
var QUEUE_TIMEOUT = 5 * time.Minute
162162

163163
func (handler *Handlers) Redirect(response http.ResponseWriter, request *http.Request) {
164-
fmt.Println(request.Header.Get("User-Agent"))
165164
shortCode := request.PathValue("shortCode")
166165
redirectionAnalytics := tasks.AnalyticsPayload{
167166
ShortCode: shortCode,
168167
UserAgent: request.Header.Get("User-Agent"),
169168
Referer: "",
170169
Timestamp: time.Now(),
171170
}
172-
fmt.Println("here ", redirectionAnalytics)
173-
fmt.Printf("abcd %+v", &redirectionAnalytics)
174171
cachedValue, redisErr := handler.redis.Get(context.Background(), shortCode).Result()
175172
if redisErr != nil {
176173
log.Error().Msgf("Error in Redis fetching short URL %v", redisErr)
@@ -180,7 +177,10 @@ func (handler *Handlers) Redirect(response http.ResponseWriter, request *http.Re
180177
if err != nil {
181178
log.Error().Msgf("Could not enqueue task: %v", err)
182179
}
183-
handler.queue.Enqueue(task, asynq.MaxRetry(MAX_QUEUE_RETRY), asynq.Timeout(QUEUE_TIMEOUT))
180+
// If the request is a GET request, enqueue the task, HEAD requests should not enqueue tasks because they are for returning header to monitoring services
181+
if request.Method == http.MethodGet {
182+
handler.queue.Enqueue(task, asynq.MaxRetry(MAX_QUEUE_RETRY), asynq.Timeout(QUEUE_TIMEOUT))
183+
}
184184
log.Info().Msgf("Value found in redis %v", cachedValue)
185185
http.Redirect(response, request, cachedValue, http.StatusFound)
186186
return
@@ -204,7 +204,10 @@ func (handler *Handlers) Redirect(response http.ResponseWriter, request *http.Re
204204
if err != nil {
205205
log.Error().Msgf("Could not enqueue task: %v", err)
206206
}
207-
handler.queue.Enqueue(task, asynq.MaxRetry(MAX_QUEUE_RETRY), asynq.Timeout(QUEUE_TIMEOUT))
207+
208+
if request.Method == http.MethodGet {
209+
handler.queue.Enqueue(task, asynq.MaxRetry(MAX_QUEUE_RETRY), asynq.Timeout(QUEUE_TIMEOUT))
210+
}
208211

209212
err = handler.redis.Set(context.Background(), shortCode, result.OriginalUrl, 0).Err()
210213
if err != nil {

0 commit comments

Comments
 (0)