Home Backend Development Golang Simple Go CLI-Everything App

Simple Go CLI-Everything App

Nov 30, 2024 pm 08:14 PM

Hey Guys!

I haven't blogged on Dev in over 2 years! It's been a while so please excuse me if my typing skills have degraded over time.

I'm currently learning Go and received a list of projects to complete and share, one of these happens to be a simple Golang cli-todo app that allows someone to add todos to a list of tasks and achieve a set of basic functionality on these tasks.

These include:

1) Listing Tasks
2) Adding More Tasks
3) Modifying These Tasks
4) Making Tasks Completed

Unfortunately, I don't have a fancy name for it ? as it's designed to be a lightweight, easy-to-use app that someone can complete in a day. Even if you're a beginner.

Simple Go CLI-Todo App

~ Project Source code: https://github.com/SirTingling/cloudprojects/tree/main/go-cli-todo-app

Let's Begin

Well as usual, the creation of our main.go. Once this is setup, we will need to define the structure and functionality of our todos. I did so in a separate todo.go

type Todo struct {
    Title       string
    Completed   bool
    CreatedAt   time.Time
    CompletedAt *time.Time
}
Copy after login
Copy after login

with a slice to hold our todos

type Todos []Todo
Copy after login
Copy after login

Then we'll need the implementation of the main methods of functionality, which include:

  • add
func (todos *Todos) add(title string) {
    todo := Todo{
        Title:       title,
        Completed:   false,
        CompletedAt: nil,
        CreatedAt:   time.Now(),
    }

    *todos = append(*todos, todo)
}
Copy after login
Copy after login

Creates a Todo object with a title, sets its Completed status to false, and appends it to the Todos slice.

  • delete
func (todos *Todos) delete(index int) error {
    t := *todos

    if err := t.validateIndex(index); err != nil {
        return err
    }

    *todos = append(t[:index], t[index+1:]...)

    return nil
}
Copy after login
Copy after login

Validates the index, then uses slicing to remove the item from the Todos list.

  • toggle
func (todos *Todos) toggle(index int) error {
    if err := todos.validateIndex(index); err != nil {
        return err
    }

    t := *todos
    todo := &t[index]

    if !todo.Completed {
        completedTime := time.Now()
        todo.CompletedAt = &completedTime
    } else {
        todo.CompletedAt = nil
    }

    todo.Completed = !todo.Completed
    return nil
}
Copy after login
Copy after login

Validates the index, flips the Completed boolean, and updates the CompletedAt timestamp accordingly.

The rest of the methods follow a very similar functionality, if any issues, feel free to check out the source code

Running The App

A common issue with many to-do apps that are cli-based is that they aren't as charming. With the help of a third-party package called aquasecurity/table the to-do list will be displayed neatly.

aquasecurity/table

It can be installed with:

go get github.com/aquasecurity/table
Copy after login

Then I made a method to display the todos using methods from external the package. Particularly SetRowLines, SetHeaders, New, AddRow & Render were the primarily used ones in my case.

func (todos *Todos) print() {
    table := table.New(os.Stdout)
    table.SetRowLines(false)
    table.SetHeaders("#", "Title", "Completed", "Created At", "Completed At")

    for index, t := range *todos {
        completed := "❌"
        completedAt := ""

        if t.Completed {
            completed = "✅"
            if t.CompletedAt != nil {
                completedAt = t.CompletedAt.Format(time.RFC1123) //time standard
            }
        }

        table.AddRow(strconv.Itoa(index), t.Title, completed, t.CreatedAt.Format(time.RFC1123), completedAt)
    }

    table.Render()
}
Copy after login

The print method is a neat way to show the list of todos in the terminal. It creates a table with columns for things like the task number, title, whether it's completed, when it was created, and when it was completed.

It goes through each todo item, checks if it's done or not, and adds a ✅ if it's completed or a ❌ if it isn't. If the task is finished, it even shows the exact date and time it was completed.

Once all the rows are ready, it prints the table out in a clean, readable format. Super handy for quickly seeing the status of all a user's tasks at a glance!

How about saving these todos?

So I thought that the functionality of saving the todos locally to let's say a file, in this case, todos.json, and then reading from there would be a good idea. Essentially having some level of persistence of our data regarding each and all todos.

We could add this functionality to an existing file, but I think it's a good idea to separate concerns.

I added a storage.go, it could be called whatever you'd like store.go, persist.go, etc.

I chose JSON but the same principles usually apply to any data format you'd like to save the data too.

type Todo struct {
    Title       string
    Completed   bool
    CreatedAt   time.Time
    CompletedAt *time.Time
}
Copy after login
Copy after login
  • There's a Storage struct that keeps track of the file being worked with.

  • The NewStorage function helps set things up by just giving it the file name.

  • The Save method takes the data, turns it into pretty JSON, and writes it to the file (todos.json). If something goes wrong, it tells us with an error.

  • The Load method does the opposite—reads the file, unpacks the JSON, and fills the fileData with the data.

It’s an easy, reusable way to handle saving and loading any kind of data without needing a database or anything fancy.

From here I make use of the NewStorage in the main.go to add some todos to my list and save them which can now be viewed in my todos.json

type Todos []Todo
Copy after login
Copy after login

func (todos *Todos) add(title string) {
    todo := Todo{
        Title:       title,
        Completed:   false,
        CompletedAt: nil,
        CreatedAt:   time.Now(),
    }

    *todos = append(*todos, todo)
}
Copy after login
Copy after login

For the commands, I didn't make anything fancy. I defined the flags I'll use as a struct

func (todos *Todos) delete(index int) error {
    t := *todos

    if err := t.validateIndex(index); err != nil {
        return err
    }

    *todos = append(t[:index], t[index+1:]...)

    return nil
}
Copy after login
Copy after login

then a simple function using the flag package the list these flags, give them more details & descriptions, and customize them. I've also heard good things about the Cobra package which could be very easy to use here, next time I'll try it out.

func (todos *Todos) toggle(index int) error {
    if err := todos.validateIndex(index); err != nil {
        return err
    }

    t := *todos
    todo := &t[index]

    if !todo.Completed {
        completedTime := time.Now()
        todo.CompletedAt = &completedTime
    } else {
        todo.CompletedAt = nil
    }

    todo.Completed = !todo.Completed
    return nil
}
Copy after login
Copy after login

From there, you can get creative on how you'd like to execute these flags, in my case I made simple case statements.

That's It?

Yep! That completed this simple Go cli to-do app that can be done in a relatively short period of time, major shout out to Coding with Patrik and The Builder both of which have amazing content out there for helping with projects like these and making it fun!

Thanks for reading and I hope that these mini-projects inspire others to either get started with Go or simply keep practicing with it. I have a few more to do and share, see you guys next time!

Simple Go CLI-Todo App

The above is the detailed content of Simple Go CLI-Everything App. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What are the vulnerabilities of Debian OpenSSL What are the vulnerabilities of Debian OpenSSL Apr 02, 2025 am 07:30 AM

OpenSSL, as an open source library widely used in secure communications, provides encryption algorithms, keys and certificate management functions. However, there are some known security vulnerabilities in its historical version, some of which are extremely harmful. This article will focus on common vulnerabilities and response measures for OpenSSL in Debian systems. DebianOpenSSL known vulnerabilities: OpenSSL has experienced several serious vulnerabilities, such as: Heart Bleeding Vulnerability (CVE-2014-0160): This vulnerability affects OpenSSL 1.0.1 to 1.0.1f and 1.0.2 to 1.0.2 beta versions. An attacker can use this vulnerability to unauthorized read sensitive information on the server, including encryption keys, etc.

What libraries are used for floating point number operations in Go? What libraries are used for floating point number operations in Go? Apr 02, 2025 pm 02:06 PM

The library used for floating-point number operation in Go language introduces how to ensure the accuracy is...

Transforming from front-end to back-end development, is it more promising to learn Java or Golang? Transforming from front-end to back-end development, is it more promising to learn Java or Golang? Apr 02, 2025 am 09:12 AM

Backend learning path: The exploration journey from front-end to back-end As a back-end beginner who transforms from front-end development, you already have the foundation of nodejs,...

What is the problem with Queue thread in Go's crawler Colly? What is the problem with Queue thread in Go's crawler Colly? Apr 02, 2025 pm 02:09 PM

Queue threading problem in Go crawler Colly explores the problem of using the Colly crawler library in Go language, developers often encounter problems with threads and request queues. �...

In Go, why does printing strings with Println and string() functions have different effects? In Go, why does printing strings with Println and string() functions have different effects? Apr 02, 2025 pm 02:03 PM

The difference between string printing in Go language: The difference in the effect of using Println and string() functions is in Go...

How to specify the database associated with the model in Beego ORM? How to specify the database associated with the model in Beego ORM? Apr 02, 2025 pm 03:54 PM

Under the BeegoORM framework, how to specify the database associated with the model? Many Beego projects require multiple databases to be operated simultaneously. When using Beego...

How to solve the user_id type conversion problem when using Redis Stream to implement message queues in Go language? How to solve the user_id type conversion problem when using Redis Stream to implement message queues in Go language? Apr 02, 2025 pm 04:54 PM

The problem of using RedisStream to implement message queues in Go language is using Go language and Redis...

PostgreSQL monitoring method under Debian PostgreSQL monitoring method under Debian Apr 02, 2025 am 07:27 AM

This article introduces a variety of methods and tools to monitor PostgreSQL databases under the Debian system, helping you to fully grasp database performance monitoring. 1. Use PostgreSQL to build-in monitoring view PostgreSQL itself provides multiple views for monitoring database activities: pg_stat_activity: displays database activities in real time, including connections, queries, transactions and other information. pg_stat_replication: Monitors replication status, especially suitable for stream replication clusters. pg_stat_database: Provides database statistics, such as database size, transaction commit/rollback times and other key indicators. 2. Use log analysis tool pgBadg

See all articles