Golang Todo App Development Guide

Author

Reads 187

A smiling adult man using a desktop computer at a desk, creating a positive work environment.
Credit: pexels.com, A smiling adult man using a desktop computer at a desk, creating a positive work environment.

Creating a Todo App in Golang is a great way to get started with the language, and it's a project that can be completed in a relatively short amount of time.

The first step is to set up a new Golang project using the go mod command. This will create a new directory for your project and initialize a Go module.

Golang's built-in net/http package is perfect for creating a simple web server to handle requests from the front-end.

A Todo App typically consists of three main components: a list of todos, a form to add new todos, and a button to delete completed todos.

Prerequisites

To get started with building a golang todo app, you need to have a basic understanding of some prerequisites.

You don't necessarily need to know Golang, but it's highly recommended to go through A Tour of Go to understand the basics of variables, loops, and if statements.

You might enjoy: Golang Go

Workplace with modern laptop with program code on screen
Credit: pexels.com, Workplace with modern laptop with program code on screen

To begin, install Docker and Golang, as Docker is required for database provision.

You should also have a basic understanding of Go, as it's the primary language used in this project.

Here's a quick rundown of what you need to know:

  • Go — Must know golang basics
  • Docker — Good to have
  • MongoDb — Good to have

To start, initialise a golang project, which will be your main server directory.

Make sure to start a mongo docker container, ideally on port 27017, or adjust the port in your code accordingly.

Database Setup

To set up your database for the GoLang Todo app, make sure you have the Docker Desktop app open. This will allow you to create a MongoDB container for database storage.

You'll need to cd into the mongo folder we created earlier and run docker compose up in the terminal. This will create the MongoDB container for you.

A MongoDB container will be created for you to use for the database storage. It's a great way to get started with database setup.

Suggestion: Golang and Mongodb

Credit: youtube.com, Go - SQL Databases in Golang with the database/sql package

To start the server, go back to the todo app project folder, open the folder in the terminal, and run go build. This will compile the code without errors.

If no database connection error is thrown, then you should see a log message from the server. This indicates that the server is running successfully.

If you encounter an error like "import \"go.mongodb.org/mongo-driver/bson\" for the undefined: bson error", don't worry! You can fix it by referencing the correct import statement.

API Setup

To set up an API for your GoLang Todo app, you'll need to create a new directory for the API and initialize a new Go module.

The first step is to create a new directory for the API and navigate into it in the terminal.

You'll then initialize a new Go module by running the command `go mod init todo-api`. This will create a new go.mod file in your directory.

Next, you'll create a new file called `main.go` and write the basic structure of your API in it, including the main function and any necessary imports.

Credit: youtube.com, Learn GO Fast: Building an API

The API will use the Gorilla MUX router to handle requests, which you can import from the `github.com/gorilla/mux` package.

You'll also need to import the `net/http` package to handle HTTP requests and responses.

To start the API, you'll run the command `go run main.go`, which will start the server and begin listening for incoming requests.

If this caught your attention, see: Golang Rest

Project Structure

The project structure for our GoLang Todo app is designed to keep things simple yet maintain independence between different layers. This is achieved through the concentric circle coding architectural style, which keeps the UI, DB, and external agents abstracted from each other.

Each directory works as an independent layer and is functional in the following ways: webservice: Handles and routes all the RESTful requests.domain: Handles all business logic.db: Communicates with the database and handles CRUD operations.main.go: This is the entry point of our application.

We also have a models directory to declare models and constants being used across all layers. The TodoListItem struct is defined in todoModels.go on a global level and shared across layers.

A Struct Type

A vast aerial landscape of desert hills in Todos Santos, Mexico, under a clear blue sky.
Credit: pexels.com, A vast aerial landscape of desert hills in Todos Santos, Mexico, under a clear blue sky.

A Struct Type is a fundamental concept in Go programming. Go is a typed language, which means that every variable has a specific data type associated with it.

You can create a Struct Type in Go by defining a collection of user-defined fields. For example, a TodoModel struct type can be created to store todo data in a MongoDB database.

Struct tags like json:"id" are used to specify the field's name, such as "id", when the struct's contents are serialized into JSON. This is important for data serialization and deserialization.

Go's typed nature makes it easier to catch errors and ensures that your code is more maintainable and efficient. By using Struct Types, you can organize your data in a clear and concise manner.

In the code, the TodoModel struct type is created with fields like id, name, and deadline. The struct tags are used to specify the field names, making it easier to work with the data.

Coding and Testing

Credit: youtube.com, Test Like a Pro in Go!

To start coding the todo functions, you first need to declare the package name inside the todo.go file and import the necessary packages. This is the foundation of building your todo application.

You'll then create two data structures: a struct item and a list type []item. The item struct will have fields like Task as string, Done as bool, CreatedAt as time.Time, and CompletedAt as time.Time.

The todo functions you'll need to implement are adding new tasks, marking tasks as complete, deleting tasks, saving the list of tasks as JSON, and getting the tasks from the JSON file.

Here's a brief overview of the todo functions:

  • Add new tasks
  • Mark tasks as complete
  • Delete tasks from the list of tasks
  • Save the list of tasks as JSON
  • Get the tasks from the JSON file

To test your todo functions, you'll create a todo_test.go file and write tests for the add function, saving and get function. You can run the tests using the go test tool.

Writing tests for the main function is also crucial, and you'll import packages and define some variables to test the Todo functions.

Get

Credit: youtube.com, Software Testing Explained in 100 Seconds

The "Get" function is a crucial part of our todo package, responsible for retrieving the saved tasks list from a JSON file.

This function uses the filename to decode and parse the JSON data into a list, handling cases where the filename doesn't exist or is an empty file.

The "Get" function is implemented in the todo.go file, where it's used to retrieve the tasks from the JSON file and return them as a list.

Here's a step-by-step breakdown of how the "Get" function works:

  • It uses the filename to open the JSON file.
  • It decodes and parses the JSON data into a list.
  • It handles cases where the filename doesn't exist or is an empty file.

The "Get" function is an essential part of our todo package, allowing us to retrieve the saved tasks list and use it in our application.

Writing Tests

Writing tests is an essential part of coding, and it's great that you're taking the time to learn about it. To write tests for your todo functions, start by creating a todo_test.go file in the same directory as your todo.go file.

Credit: youtube.com, How To Write Unit Tests (The Right Way)

You'll need to write the package name as todo_test and import the necessary packages. This will allow you to test your functions in isolation. A good practice is to test each function separately, so let's start with the add function.

Test for add function

To test the add function, you'll need to write some test code. This will involve creating a test case that covers all the possible scenarios for the add function. You can use a testing framework like Go's built-in testing package to write your tests.

Test for saving and get function

Once you've written your tests for the add function, you can move on to testing the saving and get functions. These functions are critical to the todo app, as they allow users to save and retrieve their todo items.

Here's a simple list of the steps you can follow to write tests for your todo functions:

  • Create a todo_test.go file in the same directory as your todo.go file.
  • Write the package name as todo_test and import the necessary packages.
  • Test each function separately, starting with the add function.
  • Use a testing framework like Go's built-in testing package to write your tests.

Remember, writing tests is an iterative process. You'll need to write your tests, run them, and then refactor your code to make sure it passes the tests. With practice, you'll get better at writing tests and your code will become more robust and maintainable.

CLI Functionality

Credit: youtube.com, How to Build A CLI Todo App in Go

We create the main CLI functionality by defining the main function in the main.go file.

To start, we import the necessary packages, which includes the ones we created earlier.

We then define the main function, where we'll write all our command-line functions and flags to be executed.

The main function is where the magic happens, and it's where we decide what to do based on the arguments provided.

Here's a breakdown of the main function:

  • We parse the command-line flags using a switch statement.
  • We use the parsed flags to determine what action to take, such as adding, marking as complete, or deleting tasks.

The main function is the entry point of our CLI, and it's where we bring everything together.

Here are the different actions we can perform:

These actions are the core of our CLI, and they're what make it useful for managing our tasks.

Todo App

The Todo App is built using Go programming language, specifically with the help of the go-chi router for building HTTP services. It's a lightweight and idiomatic solution for routing.

The Todo App uses MongoDB for database connection and storage. This choice allows for efficient data management and retrieval.

Credit: youtube.com, Full Golang Tutorial - Learn Go by Building a TodoList App

The Todo App has four main REST API endpoints: Create, Get, Update, and Delete. These endpoints will be used to interact with the Todo items in the database.

Here are the main CLI functionalities of the Todo App:

  • Create a new Todo item with a title
  • Get all existing Todo items
  • Update an existing Todo item
  • Delete a Todo item

The Todo App uses a custom struct type CreateTodo for the request body, which includes only the Title field. The app validates the client's input to ensure it's correct and not empty.

Broaden your view: S Golang

What We Build

We're building a Todo App, and we're going to create REST API endpoints for it. We'll have Create, Get, Update, and Delete API endpoints.

We're using Mongo DB for the database connection and storage. This will allow us to store and retrieve our Todo items efficiently.

We're using the go-chi router to build our Go HTTP service. This lightweight and idiomatic router will help us create our API endpoints.

Here are the REST API endpoints we'll be building:

  • Create: Handles HTTP POST requests to create a new Todo item.
  • Get: Handles HTTP requests to retrieve Todo items.
  • Update: Handles HTTP requests to update existing Todo items.
  • Delete: Handles HTTP requests to delete Todo items.

We'll use a custom struct type called CreateTodo for the request body of the Create endpoint. This struct will have a single field, Title, which the user will fill in.

Delete a Task

Woman in focus working on software development remotely on laptop indoors.
Credit: pexels.com, Woman in focus working on software development remotely on laptop indoors.

Deleting a task in our Todo App is a straightforward process. The code for adding tasks to the MongoDB is the same code that can be used to delete a task, but with a few modifications.

The code first decodes the request body and stores it in the to-do list model. Then, it calls the insertOneTask function and inserts the task into the collection.

However, to delete a task, we use the DELETE HTTP request instead of the POST request used for adding tasks. This is where the code for deleting a task comes in.

Here are the steps involved in deleting a task:

  • We extract the ID from the URL path using chi.URLParam(r, "id").
  • We check if the ID is a valid hex value and convert the ID from hex to primitive.ObjectID using primitive.ObjectIDFromHex(id). If the ID is invalid, we return a JSON response with a 400(Bad Request) HTTP status code and an error message indicating it’s an invalid ID.
  • If the ID is valid, we create a filter variable bson.M object to store the ID.
  • We then use db.Collection(collectionName).DeleteOne(r.Context(), filter) to find the TODO entry with that ID and delete it from the database.
  • If deleting the TODO item from the database encounters an error, we return a JSON response with a 500(Internal Server Error) and the error message indicating an error occurred while deleting the TODO item.
  • If the database successfully deleted the item, we return a JSON response with an HTTP status code 200(OK), the success message and the number of deleted entries in the database.

Nancy Rath

Copy Editor

Nancy Rath is a meticulous and detail-oriented Copy Editor with a passion for refining written content. With a keen eye for grammar, syntax, and style, she has honed her skills in ensuring that articles are polished and engaging. Her expertise spans a range of categories, including digital presentation design, where she has a particular interest in the intersection of visual and written communication.

Love What You Read? Stay Updated!

Join our community for insights, tips, and more.