Today I Learned

A collection of useful bits & bobs I'd rather not forget
A very basic goroutine example

In Golang, moving CPU intensive tasks into a Goroutine is a very easy way to process heavy tasks concurrently but synchronously. Imagine you're uploading a file to S3. Written as below, this would run in the main channel:

func main() {
  // ...
  imageUrl := HeavyImageUpload(imageData)
  return imageUrl
}
func HeavyImageUpload(imageData ImageData) {
  //... image processing stuff
  return imageUrl
}

This will work, but it won't scale well. However, you can easily move this into it's own channel away from the main channel, meaning they can be processed at the same time, but remain in sync.

func main() {
  // ...
  imageChannel := make(chan string)
  // Run function within a goroutine
  go HeavyImageUpload(imageData, imageChannel)
  // Wait for the channel
  imageUrl := <- imageChannel 
  return imageUrl
}
func HeavyImageUpload(imageData ImageData, imageChannel chan string) {
  //... image processing stuff
  imageChannel <- imageUrlString
}

The <- pointers are key. They ensure that the channel has finished processing before moving on to the next part of the program.

This is a great way of still performing everything synchronously, but moving the processing into parallel threads so they can be processed concurrently.

GOLANG
Things I learned on other days →