Section 1. Defining the Product Data Structure and Creating a Basic HTTP Server
We start by defining a product type as a struct. Each product consists of an ID, Name, Quantity, and Price. Then, we set up a basic HTTP server with a homepage endpoint.Section 2. Adding Endpoints and Returning JSON Data
We now introduce a new endpoint to return all products in JSON format. The Goencoding/json package encodes our data seamlessly.
http://localhost:10000/products, the API returns the JSON-encoded list of products:
Section 3. Retrieving a Specific Product by ID
Next, we implement an endpoint to fetch a specific product based on its ID by slicing the URL path.http://localhost:10000/product/1 logs the URL and returns the matching product in JSON format.
──────────────────────────────
Section 4. Introducing Gorilla Mux for Advanced Routing
While the standard library works well for basic routing, slicing URL strings is not the most elegant solution. To simplify route handling and support dynamic URL variables, we integrate the Gorilla Mux router. Gorilla Mux is one of the most popular routing packages in the Go ecosystem. It supports method-based routing and lets you define route variables using patterns like/movies/{id}, where {id} is dynamically extracted from the URL.


To install Gorilla Mux, run the command:go get github.com/gorilla/mux
http.ListenAndServe:
http://localhost:10000/product/2 will return a JSON response similar to:
Summary
In this article, we built a RESTful API in Go using the following steps:- Defined a product struct and maintained an in-memory data slice.
- Created basic endpoints with the net/http package to return all products and a specific product by ID.
- Enhanced the API by integrating the Gorilla Mux router for more efficient route handling and dynamic URL variable extraction.