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.
~ Project Source code: https://github.com/SirTingling/cloudprojects/tree/main/go-cli-todo-app
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:
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.
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.
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
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!
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.
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!
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!