Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 17 additions & 1 deletion handlers/scrape.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@ package handlers

import (
"crypto/tls"
"errors"
"fmt"
"net"
"net/http"
"net/url"
"strconv"
Expand Down Expand Up @@ -52,8 +54,22 @@ func ScrapeHandler(context *gin.Context) {
pageInfo, err := services.FetchPageInfo(client, baseURL)
if err != nil {
logger.Error(err)
var netErr net.Error

if errors.As(err, &netErr) {
if netErr.Timeout() {
context.JSON(http.StatusGatewayTimeout,
utils.BuildErrorResponse("Request timeout during the page fetch"))
return
} else {
context.JSON(http.StatusBadGateway,
utils.BuildErrorResponse("Failed to reach the requested URL"))
return
}
}

context.JSON(http.StatusInternalServerError,
utils.BuildErrorResponse("Failed to fetch page info"))
utils.BuildErrorResponse("An unexpected error occurred"))
return
}

Expand Down
48 changes: 46 additions & 2 deletions handlers/scrape_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package handlers

import (
"encoding/json"
"net"
"net/http"
"net/http/httptest"
"scraper/models"
Expand Down Expand Up @@ -54,7 +55,7 @@ func TestScrapeHandler(test_type *testing.T) {
},
},
{
name: "Error Fetching Page Info",
name: "Unexpected Error Fetching Page Info",
queryParams: map[string]string{
"url": "http://example.com",
},
Expand All @@ -63,7 +64,50 @@ func TestScrapeHandler(test_type *testing.T) {
mockRequestID: "",
expectedStatus: http.StatusInternalServerError,
expectedBody: map[string]interface{}{
"error": "Failed to fetch page info",
"error": "An unexpected error occurred",
},
},
{
name: "Timeout Error Fetching Page Info",
queryParams: map[string]string{
"url": "http://example.com",
},
mockPageInfo: nil,
mockError: &net.DNSError{
IsTimeout: true,
},
mockRequestID: "",
expectedStatus: http.StatusGatewayTimeout,
expectedBody: map[string]interface{}{
"error": "Request timeout during the page fetch",
},
},
{
name: "Failed to Reach The Request URL",
queryParams: map[string]string{
"url": "http://example.com",
},
mockPageInfo: nil,
mockError: &net.DNSError{
IsTimeout: false,
},
mockRequestID: "",
expectedStatus: http.StatusBadGateway,
expectedBody: map[string]interface{}{
"error": "Failed to reach the requested URL",
},
},
{
name: "Failed to Reach The Request URL",
queryParams: map[string]string{
"url": "http://example",
},
mockPageInfo: nil,
mockError: nil,
mockRequestID: "",
expectedStatus: http.StatusBadRequest,
expectedBody: map[string]interface{}{
"error": "Invalid URL format, please provide a valid URL.",
},
},
}
Expand Down
Loading