search
HomeBackend DevelopmentGolangSimple Go CLI-Everything App

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
}

with a slice to hold our todos

type Todos []Todo

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)
}

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
}

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
}

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

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()
}

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
}
  • 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

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

    *todos = append(*todos, todo)
}

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
}

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
}

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
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
Security Considerations When Developing with GoSecurity Considerations When Developing with GoApr 27, 2025 am 12:18 AM

Gooffersrobustfeaturesforsecurecoding,butdevelopersmustimplementsecuritybestpracticeseffectively.1)UseGo'scryptopackageforsecuredatahandling.2)Manageconcurrencywithsynchronizationprimitivestopreventraceconditions.3)SanitizeexternalinputstoavoidSQLinj

Understanding Go's error InterfaceUnderstanding Go's error InterfaceApr 27, 2025 am 12:16 AM

Go's error interface is defined as typeerrorinterface{Error()string}, allowing any type that implements the Error() method to be considered an error. The steps for use are as follows: 1. Basically check and log errors, such as iferr!=nil{log.Printf("Anerroroccurred:%v",err)return}. 2. Create a custom error type to provide more information, such as typeMyErrorstruct{MsgstringDetailstring}. 3. Use error wrappers (since Go1.13) to add context without losing the original error message,

Error Handling in Concurrent Go ProgramsError Handling in Concurrent Go ProgramsApr 27, 2025 am 12:13 AM

ToeffectivelyhandleerrorsinconcurrentGoprograms,usechannelstocommunicateerrors,implementerrorwatchers,considertimeouts,usebufferedchannels,andprovideclearerrormessages.1)Usechannelstopasserrorsfromgoroutinestothemainfunction.2)Implementanerrorwatcher

How do you implement interfaces in Go?How do you implement interfaces in Go?Apr 27, 2025 am 12:09 AM

In Go language, the implementation of the interface is performed implicitly. 1) Implicit implementation: As long as the type contains all methods defined by the interface, the interface will be automatically satisfied. 2) Empty interface: All types of interface{} types are implemented, and moderate use can avoid type safety problems. 3) Interface isolation: Design a small but focused interface to improve the maintainability and reusability of the code. 4) Test: The interface helps to unit test by mocking dependencies. 5) Error handling: The error can be handled uniformly through the interface.

Comparing Go Interfaces to Interfaces in Other Languages (e.g., Java, C#)Comparing Go Interfaces to Interfaces in Other Languages (e.g., Java, C#)Apr 27, 2025 am 12:06 AM

Go'sinterfacesareimplicitlyimplemented,unlikeJavaandC#whichrequireexplicitimplementation.1)InGo,anytypewiththerequiredmethodsautomaticallyimplementsaninterface,promotingsimplicityandflexibility.2)JavaandC#demandexplicitinterfacedeclarations,offeringc

init Functions and Side Effects: Balancing Initialization with Maintainabilityinit Functions and Side Effects: Balancing Initialization with MaintainabilityApr 26, 2025 am 12:23 AM

Toensureinitfunctionsareeffectiveandmaintainable:1)Minimizesideeffectsbyreturningvaluesinsteadofmodifyingglobalstate,2)Ensureidempotencytohandlemultiplecallssafely,and3)Breakdowncomplexinitializationintosmaller,focusedfunctionstoenhancemodularityandm

Getting Started with Go: A Beginner's GuideGetting Started with Go: A Beginner's GuideApr 26, 2025 am 12:21 AM

Goisidealforbeginnersandsuitableforcloudandnetworkservicesduetoitssimplicity,efficiency,andconcurrencyfeatures.1)InstallGofromtheofficialwebsiteandverifywith'goversion'.2)Createandrunyourfirstprogramwith'gorunhello.go'.3)Exploreconcurrencyusinggorout

Go Concurrency Patterns: Best Practices for DevelopersGo Concurrency Patterns: Best Practices for DevelopersApr 26, 2025 am 12:20 AM

Developers should follow the following best practices: 1. Carefully manage goroutines to prevent resource leakage; 2. Use channels for synchronization, but avoid overuse; 3. Explicitly handle errors in concurrent programs; 4. Understand GOMAXPROCS to optimize performance. These practices are crucial for efficient and robust software development because they ensure effective management of resources, proper synchronization implementation, proper error handling, and performance optimization, thereby improving software efficiency and maintainability.

See all articles

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

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools