go-mongo-crud-rest-api
go-mongo-crud-rest-api copied to clipboard
CRUD operations on MongoDB using Golang (REST API)
This is CRUD operations on MongoDB written in Golang. You can create, read, update, and delete users from the MongoDB instance using http requests.
How to run?
First, start a MongoDB instance using docker:
docker run --name mongodb -d -p 27017:27017 mongo
Next, clone the repository:
git clone [email protected]:parsaakbari1209/go-mongo-crud-rest-api.git
Next, change the current directory to the repository:
cd go-mongo-crud-rest-api
Next, install the dependencies:
go get ./...
Finally, run the app on port 9080
:
go run .
Endpoints:
GET /users/:email
POST /users
PUT /users/:email
DELETE /users/:email
Get User
This endpoint retrieves a user given the email.
Send a GET
request to /users/:email
:
curl -X GET 'http://127.0.0.1:9080/users/[email protected]'
Response:
{
"user": {
"id": "<user_id>",
"name": "Bob",
"email": "[email protected]",
"password": "ilovealice"
}
}
Create User
This endpoint inserts a document in the users
collection of the users
database.
Send a POST
request to /users
:
curl -X POST 'http://127.0.0.1:9080/users' -H "Content-Type: application/json" -d '{"name": "Bob", "email": "[email protected]", "password": "ilovealice"}'
Response:
{
"user": {
"id": "<user_id>",
"name": "Bob",
"email": "[email protected]",
"password": "ilovealice"
}
}
Update User
This endpoint updates the provided fields within the specified document filtered by email.
Send a PUT
request to /users/:email
:
curl -X PUT 'http://127.0.0.1:9080/users/[email protected]' -H "Content-Type: application/json" -d '{"password": "loveyoualice"}'
Response:
{
"user": {
"id": "<user_id>",
"name": "Bob",
"email": "[email protected]",
"password": "loveyoualice"
}
}
Delete User
This endpoint deletes the user from database given the email.
Send a DELETE
request to /users/:email
:
curl -X DELETE 'http://127.0.0.1:9080/users/[email protected]'
Response:
{}
Errors
All of the endpoints return an error in json format with a proper http status code, if something goes wrong:
{
"error": "user not found"
}
Conventions
Here is a list of conventions used:
Contributing
Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.
Please make sure to update tests as appropriate.