You can do this in many ways, but you can also do it like this:

Start a goroutine and use channels to communicate and coordinate reading/writing. Use defer in the goroutine.