Home
Go Back
Introduction
In this post, we'll go through step-by-step on how to create this cool soccer header loading animation in the terminal. Here is a summary of things we will cover:
- Write to stdout
- Clear line in the terminal
- Hide/show the cursor
- Enable raw input mode
Write to stdout
Here is a short Go program that writes bytes to stdout. We will be using the adult emoji 🧑 in this example. We refer to the ascii table to get the hex value for the new line control character. To get the utf-8 code units for the '🧑' emoji, we can use the unicode code converter tool.
Clear the terminal
To clear a line in the terminal, we can use the ansi escape code ESC[2K
— this will clear the entire line — followed by ESC[G
— this will move the cursor to the beginning of the line.
Soccer header animation
Now that we know how to clear a line in the terminal, we can use this to create a soccer header animation. We will print a frame every 100 milliseconds.
Hide/show the cursor
If you look at the gif above, you can see the cursor at the start of the line. We can remove it to make it look nicer.
To hide the cursor, we can use the ansi escape code ESC[?25l
and to show it again when the program ends, we can use ESC[?25h
.
To decide when to show back the cursor, we can use the defer statement or listen to the interrupt signal. In the example below, we will use the interrupt signal approach.
Bonus: Enabling raw input mode
You might notice that if you were to press 'enter' whilst the animation is running, it may mess up the output. This is because the terminal is in cooked mode by default. To fix this, we can enable raw input mode by using the termios library. This will allow us to read the input character by character instead of line by line. Below is an example of how to do this on macos.