Command-line todo list written in Golang
By Steve Claridge on 2015-05-26.
This is the output from my quick look at Golang. It is a simple command-line todo list that lets you add, delete and view your todo items. I'm sure the code can be improved in many places, I'm new to Go. Here's the source:
package main import (
"fmt"
"os"
"strconv"
"bufio"
) // Read all lines from the given file and return as an array of strings. Returns an empty array
// if there was a problem reading the file.
func readFile( filename string ) []string {
file, err := os.Open( filename )
if err != nil {
return []string{}
}
defer file.Close()
scanner := bufio.NewScanner( bufio.NewReader( file ) ) var tmp []string
for scanner.Scan() {
tmp = append( tmp, scanner.Text() )
}
return tmp
} // Write the given string array to the specified file, overwriting any lines
// that were previously in the file.
func writeFile( filename string, lines []string ) {
file, err := os.Create( filename ) //example of multiple results from a function where one is the error code
if err != nil {
panic( "could not open todo file" )
}
defer file.Close() //will call file's close function at the end of writeFile
w := bufio.NewWriter( file )
defer w.Flush() //interesting, two deferred funcs, one needs to be called first....
for _, each := range lines { //ignore the first param with "_"
fmt.Fprint( w, each + "\n" )
}
} // Displays list of todo items and their index within the list, for example:
//
// 0. First todo item
// 1. Remember the milk
// 2. Make some stuff
//
func show( arr []string ) {
for index, each := range arr {
fmt.Printf( "%d. %s \n", index, each )
}
} // Remove the element from the given array as specified by index i. If i is greater
// than size of array then just return the array as-is with no deletion.
func deleteIt( i int, arr []string ) []string {
if i < len( arr ) {
return append( arr[:i], arr[i+1:]... ) // https://blog.golang.org/slices
} else {
return arr
}
} // Main entry point of the application.
//
// If a user runs app with no paraemeters then it shows all todo list items.
// If a user passes a string then it adds string to the list of todo items and then displays the list.
// If a user passes a number then it deletes that item from the list (zero based) and then displays the list.
func main() {
lines := readFile( "/tmp/todo.dat" ) //improve this by using a constant for filename
args := os.Args[1:] //Ignore element 0, which is the program name if len( args ) > 0 {
n, err := strconv.Atoi( args[0] )
if err == nil {
lines = deleteIt( n, lines )
} else {
lines = append( lines, args[0] )
}
}
show( lines )
writeFile( "/tmp/todo.dat", lines ) //improve this by using a constant for filename
}
Some examples of using the app from the command-line in Windows: