In this guide, we will create a simple web API using Go, which will include basic operations such as creating, reading, updating, and deleting (CRUD) data. We will be using the net/http package for the API and demonstrate how to set up routing and handlers. Additionally, the repository will be accompanied by a README.md file explaining the project setup and structure.
We will create a RESTful API that can manage a list of users. The API will expose the following endpoints:
GET/users: Fetch all users.
GET/users/{id}: Fetch a specific user by ID.
POST/users: Create a new user.
PUT/users/{id}: Update an existing user by ID.
DELETE/users/{id}: Delete a user by ID.
Step 1: Initialize a Go Module
Start by initializing a Go module for your project:
Step 2: Set Up the Main File
Create a file named main.go where we will define our API routes and handlers:
Step 3: Install Dependencies
To manage routing in our API, we will use the gorilla/mux package. Install it by running:
Step 4: Run the Application
After writing the code, you can run the API server:
The API will start running on http://localhost:8080.