Simplify Your Links: Building URL Shortener with Go and GoFr

Ever wanted to build your own URL shortener? In this article, we’ll guide you through creating one using Go, a powerful and popular programming language, and GoFr, a developer-friendly framework that simplifies web development in Go.What is a URL short…


This content originally appeared on Level Up Coding - Medium and was authored by Mundhraumang

Ever wanted to build your own URL shortener? In this article, we’ll guide you through creating one using Go, a powerful and popular programming language, and GoFr, a developer-friendly framework that simplifies web development in Go.

What is a URL shortener?

A URL shortener is a simple tool that takes a long URL and transforms it into a short URL. This is incredibly useful in today’s digital age where sharing links has become a daily routine. With a URL shortener, you can easily share links that are concise and more manageable.

Why Go and GoFr?

Go is known for its speed, efficiency, and clean syntax, making it a great choice for web applications. GoFr is an opinionated web framework for Go that simplifies the process of building web applications. With its intuitive design and powerful features, GoFr allows developers to focus on writing clean, maintainable code without getting bogged down by boilerplate.

GoFr’s simplicity and efficiency align perfectly with Go’s philosophy, making them a powerful duo for our URL shortener project.

Design & Directory Structure:

Shortening Process:

When a user submits a long URL, the application will generate a unique short code (e.g. random alphanumeric string) and store the long URL and its corresponding short code in a Redis key-value store. It will then return the generated short URL to the user.

Redirection:

When a user accesses a shortened URL, the application will retrieve the original long URL from Redis using the short code. At end, application will redirect the user’s browser to the original long URL.

url-shortener/
├── config/
│ └── config.env # Environment variables for application settings (e.g., Redis connection details)
├── handlers/
│ └── handlers.go # Handlers for processing URL shortening requests and redirecting users based on short code
├── models/
│ └── url.go
| # Model representing a shortened URL and its original URL
├── main.go # Application entry point
└── go.mod

Building the URL Shortener with GoFr:

Dependencies:

Before we start coding, let’s discuss the dependencies we need for our application. The primary dependency is, of course, GoFr. GoFr provides a fluent API for defining routes and comes with built-in support for redis database, making it an ideal choice for our URL shortener project. To install GoFr, we can use the following command:

go get github.com/gofr/gofr

Code Overview:

Now that we have a clear design and understand GoFr’s role, let’s delve into the code that brings our URL shortener to life. In this section, we’ll walk through the main components of our URL shortener application. We’ll focus on the handlers, which are the heart of our application, and how GoFr is used to simplify the development process.

Handlers:

Our application has two main handlers: ShortenURLHandler and RedirectHandler. These handlers are responsible for shortening URLs and redirecting shortened URLs to their original URLs, respectively.

ShortenURLHandler:

The ShortenURLHandler takes a URL from the request, generates a shortened URL, stores the mapping in the Redis database, and returns the shortened URL in the response. Here’s a brief overview of how it works:

// ShortenURLHandler handles the shortening of URLs
func ShortenURLHandler(ctx *gofr.Context) (interface{}, error) {
var (
req models.Response
id string
)

err := ctx.Bind(&req)
if err != nil {
ctx.Logger.Errorf("error in binding the request. err : %v", err)
return nil, err
}

// Parse URL from request
parsedURL, err := url.ParseRequestURI(req.URL)
if err != nil {
ctx.Logger.Errorf("malformed or invalid url in request.")
return nil, err
}

// Generate custom short code or use provided one
if req.CustomShort == "" {
id = base62Encode(rand.Uint64())
} else {
id = req.CustomShort
}

// Set default expiry if not provided
if req.Expiry == 0 {
req.Expiry = expiryHours
}

// Store URL and short code in Redis with expiry
err = ctx.Redis.Set(ctx, id, parsedURL, req.Expiry*3600*time.Second).Err()
if err != nil {
ctx.Logger.Errorf("error while inserting data into redis. err : %v", err)
return nil, err
}

// Populate response object
resp := models.Response{
URL: req.URL,
CustomShort: id,
Expiry: req.Expiry,
}

return resp, nil
}

RedirectHandler:

The RedirectHandler takes a short URL from the request, retrieves the original URL from the Redis database, and returns the original URL in the response. Here’s a brief overview of how it works:

// RedirectHandler handles the redirection of short URLs
func RedirectHandler(ctx *gofr.Context) (interface{}, error) {
inputURL := ctx.PathParam("url")

// Retrieve URL from Redis based on short code
value, err := ctx.Redis.Get(ctx, inputURL).Result()
switch {
case errors.Is(err, redis.Nil):
ctx.Logger.Errorf("short URL not found in database")
return nil, errors.New("short URL not found in database")
case err != nil:
ctx.Logger.Errorf("unable to fetch the URL from Redis: %v", err)
return nil, err
}

return &models.RedirectResponse{OriginalURL: value}, nil
}

Models:

Our application uses two main models: Response and RedirectResponse. The Response model is used for the shortening URL requests and responses, while the RedirectResponse model is used for the redirecting URL responses.

type Response struct {
URL string `json:"url"`
CustomShort string `json:"short"`
Expiry time.Duration `json:"expiry"`
}

type RedirectResponse struct {
OriginalURL string `json:"original_url"`
}

Main Function:

The main function of our application sets up the GoFr application, registers the handlers, and starts the application. It uses GoFr’s New function to create a new GoFr application, the POST and GET methods to register the ShortenURLHandler and RedirectHandler, respectively, and the Run method to start the application.

func main() {
app := gofr.New()

app.POST("/shorten", handlers.ShortenURLHandler)
app.GET("/{url}", handlers.RedirectHandler)

app.Run()
}

Additional Notes:

  • The base62Encode function (not shown here) ensures that the generated short codes only contain alphanumeric characters, making them URL-safe. Its implementation is provided in handlers source file (handlers/handlers.go).
  • Error handling is implemented in both handlers to gracefully handle invalid URLs, missing short codes in Redis, and other potential issues.
Sample Request and Response for POST endpoint of our URL Shortener

Simplifying Development with GoFr

  1. Clear Separation of Concerns: GoFr encourages a modular approach by separating handlers for HTTP requests and models for data structures. This enhances code organization and maintainability.
  2. Configuration-Driven Approach: By leveraging environment variables or configuration files, GoFr streamlines setup tasks like database connections and server configurations, reducing boilerplate code.
  3. Concise Routing Definition: With GoFr’s fluent routing API, defining routes becomes intuitive and straightforward, aiding in better code readability and navigation.
  4. Monitoring and Observability: Built-in support for metrics and tracing in GoFr facilitates monitoring application health and performance, enabling effective issue diagnosis. User can enable the observability in GoFr application by referring to GoFr’s documentation.
  5. Simplified Development: GoFr’s intuitive framework and adherence to best practices expedite development cycles, allowing developers to focus on business logic rather than infrastructure concerns.

In conclusion, GoFr offers a host of benefits that simplify the development process, making it a great choice for building web applications in Go.

Conclusion:

We’ve journeyed through the process of building a URL shortener using Go and GoFr, exploring the benefits of GoFr’s simplicity and efficiency along the way. We’ve seen how GoFr encourages a clear separation of concerns, reduces boilerplate code with its configuration-driven approach, provides a concise way to define routes, and simplifies monitoring with built-in support.

The full code for the URL shortener application we discussed is available on GitHub.

Remember, the beauty of programming lies in its creativity and endless possibilities. Don’t be afraid to experiment, make mistakes, and learn. Whether you’re building a simple URL shortener or a complex microservice architecture, GoFr can be a valuable tool in your developer toolkit.

So go ahead, start your journey with GoFr, build more projects, and experience the joy of simplified development. Happy coding!

Do checkout GoFr and it’s Github Repo and support it by giving it a ⭐.


Simplify Your Links: Building URL Shortener with Go and GoFr was originally published in Level Up Coding on Medium, where people are continuing the conversation by highlighting and responding to this story.


This content originally appeared on Level Up Coding - Medium and was authored by Mundhraumang


Print Share Comment Cite Upload Translate Updates
APA

Mundhraumang | Sciencx (2024-06-20T14:07:18+00:00) Simplify Your Links: Building URL Shortener with Go and GoFr. Retrieved from https://www.scien.cx/2024/06/20/simplify-your-links-building-url-shortener-with-go-and-gofr/

MLA
" » Simplify Your Links: Building URL Shortener with Go and GoFr." Mundhraumang | Sciencx - Thursday June 20, 2024, https://www.scien.cx/2024/06/20/simplify-your-links-building-url-shortener-with-go-and-gofr/
HARVARD
Mundhraumang | Sciencx Thursday June 20, 2024 » Simplify Your Links: Building URL Shortener with Go and GoFr., viewed ,<https://www.scien.cx/2024/06/20/simplify-your-links-building-url-shortener-with-go-and-gofr/>
VANCOUVER
Mundhraumang | Sciencx - » Simplify Your Links: Building URL Shortener with Go and GoFr. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2024/06/20/simplify-your-links-building-url-shortener-with-go-and-gofr/
CHICAGO
" » Simplify Your Links: Building URL Shortener with Go and GoFr." Mundhraumang | Sciencx - Accessed . https://www.scien.cx/2024/06/20/simplify-your-links-building-url-shortener-with-go-and-gofr/
IEEE
" » Simplify Your Links: Building URL Shortener with Go and GoFr." Mundhraumang | Sciencx [Online]. Available: https://www.scien.cx/2024/06/20/simplify-your-links-building-url-shortener-with-go-and-gofr/. [Accessed: ]
rf:citation
» Simplify Your Links: Building URL Shortener with Go and GoFr | Mundhraumang | Sciencx | https://www.scien.cx/2024/06/20/simplify-your-links-building-url-shortener-with-go-and-gofr/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.