From 2a47a67fbd314efe9a52e1f0f9cec3d0716b0296 Mon Sep 17 00:00:00 2001 From: Arkaprabha Chakraborty Date: Tue, 6 Aug 2024 03:42:43 +0530 Subject: [PATCH] Fix: correct domain is used for the short url --- backend/main.go | 41 +++++++++++++++++++++++++++++++++++------ frontend/app/page.js | 24 +++++++++++++++++------- 2 files changed, 52 insertions(+), 13 deletions(-) diff --git a/backend/main.go b/backend/main.go index f2a5157..5bc43bb 100644 --- a/backend/main.go +++ b/backend/main.go @@ -50,14 +50,43 @@ func generateRandomString(length int) string { } func shortenURL(c echo.Context) error { - url := new(URL) - if err := c.Bind(url); err != nil { + // Define a struct for binding the request body + type RequestBody struct { + LongURL string `json:"long_url"` + BaseURL string `json:"base_url"` // Expect base URL in the request + } + + // Bind request body to the RequestBody struct + reqBody := new(RequestBody) + if err := c.Bind(reqBody); err != nil { return err } - url.CreatedAt = time.Now() - url.ID = generateRandomString(6) - url.ShortURL = "http://localhost:3000/" + url.ID - db.Create(url) + + // Validate the base URL + if reqBody.BaseURL == "" { + // Fallback to BASE_URL environment variable + reqBody.BaseURL = os.Getenv("BASE_URL") + if reqBody.BaseURL == "" { + return echo.NewHTTPError(http.StatusInternalServerError, "Base URL is not configured") + } + } + + // Generate a unique ID + id := generateRandomString(6) + + // Create URL record + url := &URL{ + ID: id, + LongURL: reqBody.LongURL, + ShortURL: reqBody.BaseURL + "/" + id, + CreatedAt: time.Now(), + } + + // Save URL record to the database + if err := db.Create(url).Error; err != nil { + return echo.NewHTTPError(http.StatusInternalServerError, "Failed to create URL record") + } + return c.JSON(http.StatusCreated, url) } diff --git a/frontend/app/page.js b/frontend/app/page.js index e1bd5d1..a30cf6f 100644 --- a/frontend/app/page.js +++ b/frontend/app/page.js @@ -12,13 +12,23 @@ export default function Home() { const handleSubmit = async (e) => { e.preventDefault(); - const response = await axios.post( - `${process.env.NEXT_PUBLIC_BACKEND_URL}/reduce/shorten`, - { - long_url: longUrl, - }, - ); - setShortUrl(response.data.short_url); + + // Use the frontend domain as the base URL + const baseURL = window.location.origin; + + try { + const response = await axios.post( + `${process.env.NEXT_PUBLIC_BACKEND_URL}/reduce/shorten`, + { + long_url: longUrl, + base_url: baseURL, // Include the frontend domain in the request body + }, + ); + + setShortUrl(response.data.short_url); + } catch (error) { + console.error("Error shortening URL:", error); + } }; return (