DEV Community

Cover image for Simple Go CLI-Todo App
Jordan Tingling
Jordan Tingling

Posted on

Simple Go CLI-Todo 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.

Image description

~ 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
}
Enter fullscreen mode Exit fullscreen mode

with a slice to hold our todos

type Todos []Todo
Enter fullscreen mode Exit fullscreen mode

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)
}
Enter fullscreen mode Exit fullscreen mode

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
}
Enter fullscreen mode Exit fullscreen mode

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
}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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()
}
Enter fullscreen mode Exit fullscreen mode

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.

package main

import (
    "encoding/json"
    "os"
)

type Storage[T any] struct {
    Filename string
}

func NewStorage[T any](filename string) *Storage[T] {
    return &Storage[T]{Filename: filename}
}

func (s *Storage[T]) Save(data T) error {
    fileData, err := json.MarshalIndent(data, "", "    ")
    if err != nil {
        return err
    }

    return os.WriteFile(s.Filename, fileData, 0644) // file mode
}

func (s Storage[T]) Load(data *T) error {
    fileData, err := os.ReadFile(s.Filename)
    if err != nil {
        return err
    }

    return json.Unmarshal(fileData, data) // convert and populate data
}
Enter fullscreen mode Exit fullscreen mode
  • 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

func main() {
    todos := Todos{}
    // Load data (todos) from storage:
    storage := NewStorage[Todos]("todos.json")
    err := storage.Load(&todos)
    if err != nil {
        fmt.Println("Warning: Could not load todos from storage. Starting fresh todos.")
    }
    // Parse & Execute
    cmdFlags := NewCmdFlags()
    cmdFlags.Execute(&todos)
    // Save to storage
    err = storage.Save(todos)
    if err != nil {
        fmt.Printf("Error saving todos in storage: %v\n", err)
    }
}
Enter fullscreen mode Exit fullscreen mode

[
    {
        "Title": "Go for a drive",
        "Completed": false,
        "CreatedAt": "2024-11-26T15:26:06.691069-05:00",
        "CompletedAt": null
    },
    {
        "Title": "Eat dinner",
        "Completed": true,
        "CreatedAt": "2024-11-26T15:26:37.361324-05:00",
        "CompletedAt": "2024-11-26T15:33:03.088908-05:00"
    },
    {
        "Title": "Walk my dog",
        "Completed": false,
        "CreatedAt": "2024-11-27T17:44:04.963474-05:00",
        "CompletedAt": null
    },
    {
        "Title": "Go hiking later with ashley",
        "Completed": false,
        "CreatedAt": "2024-11-27T17:51:01.667686-05:00",
        "CompletedAt": null
    }
]
Enter fullscreen mode Exit fullscreen mode

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

type CmdFlags struct {
    Add    string
    Del    int
    Edit   string
    Toggle int
    List   bool
}
Enter fullscreen mode Exit fullscreen mode

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 NewCmdFlags() *CmdFlags {
    cf := CmdFlags{}

    // Flag list and usage of cli todo app
    flag.StringVar(&cf.Add, "add", "", "Add a new todo specifying title")
    flag.StringVar(&cf.Edit, "edit", "", "Edit a todo by index & specify a new title. id:new_title")
    flag.IntVar(&cf.Del, "del", -1, "Specify a todo by index to delete effectively")
    flag.IntVar(&cf.Toggle, "toggle", -1, "Specify a todo by index to toggle")
    flag.BoolVar(&cf.List, "list", false, "List all todos")
    //
    flag.Parse()

    return &cf
}
Enter fullscreen mode Exit fullscreen mode

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!

Image description

Top comments (0)