Golang CRUD Web Server with PostgreSQL
Introduction
This project is a simple CRUD (Create, Read, Update, Delete) web server implemented in Golang, with a PostgreSQL database for storage. It demonstrates how to build a RESTful API using Go and Gorilla Mux, and how to interact with a PostgreSQL database. The server supports basic CRUD operations on a users
table.
Table of Contents
- Features
- Prerequisites
- Installation
- Usage
- API Endpoints
- Running Tests
- Contributing
- License
Features
- Create User: Add a new user to the database.
- Read User: Retrieve user details by ID.
- Update User: Modify existing user details by ID.
- Delete User: Remove a user from the database by ID.
Prerequisites
Installation
-
Clone the repository:
git clone https://github.com/yourusername/golang-crud-webserver.git
cd golang-crud-webserver
-
Create the init.sql
file:
CREATE TABLE users (
id SERIAL PRIMARY KEY,
name VARCHAR(100),
email VARCHAR(100)
);
-
Ensure the project directory structure is as follows:
golang-crud-webserver/
├── Dockerfile
├── docker-compose.yml
├── go.mod
├── go.sum
├── init.sql
└── main.go
-
Build and run the containers:
docker-compose up --build
This command will build the Docker images and start the containers for the application and PostgreSQL database.
Usage
Accessing the API
The web server runs on http://localhost:8080
. You can interact with the API using tools like curl
or Postman.
Example curl
Commands
-
Create a User:
curl -X POST -H "Content-Type: application/json" -d '{"name":"John Doe", "email":"john@example.com"}' http://localhost:8080/users
-
Get a User:
curl http://localhost:8080/users/1
-
Update a User:
curl -X PUT -H "Content-Type: application/json" -d '{"name":"Jane Doe", "email":"jane@example.com"}' http://localhost:8080/users/1
-
Delete a User:
curl -X DELETE http://localhost:8080/users/1
API Endpoints
1. Create a User
- URL:
/users
- Method:
POST
- Body:
{
"name": "John Doe",
"email": "john@example.com"
}
- Response:
{
"id": 1,
"name": "John Doe",
"email": "john@example.com"
}
2. Get a User
3. Update a User
- URL:
/users/{id}
- Method:
PUT
- Body:
{
"name": "Jane Doe",
"email": "jane@example.com"
}
- Response:
{
"id": 1,
"name": "Jane Doe",
"email": "jane@example.com"
}
4. Delete a User
- URL:
/users/{id}
- Method:
DELETE
- Response:
204 No Content
Running Tests
Currently, this project does not include automated tests. You can test the API manually using curl
commands or Postman as described in the Usage section.
Contributing
Contributions are welcome! Please fork the repository and submit a pull request with your changes. Ensure your code adheres to the existing style and includes appropriate documentation.
License
This project is licensed under the MIT License. See the LICENSE file for details.