Skip to content

Instantly share code, notes, and snippets.

@ivan-marquez
Last active July 24, 2019 19:26
Show Gist options
  • Save ivan-marquez/a9a492abcf064f31ec6a9e4399c29194 to your computer and use it in GitHub Desktop.
Save ivan-marquez/a9a492abcf064f31ec6a9e4399c29194 to your computer and use it in GitHub Desktop.
Simple goroutines and channels implementation for concurrent processing.
/*
* Package statuschecker checks the status of a given url and prints the online status
* to the console.
*/
package main
import (
"fmt"
"net/http"
"time"
)
func main() {
links := []string{
"https://google.com",
"https://facebook.com",
"https://stackoverflow.com",
"https://golang.org",
"https://amazon.com",
}
// Channels are used to communicate in between different running go routines
c := make(chan string)
for _, link := range links {
go checkLink(link, c)
}
// using a range with a channel allows us to retrieve a value sent
// to the channel and assign it to a variable.
for l := range c {
// l variable is defined in the outer scope of the function literal and maintained
// by another goroutine. In order to share this variable with other goroutines, we need
// to pass it as an argument to a function literal so they receive a copy of it.
go func(link string) {
time.Sleep(3 * time.Second)
checkLink(link, c)
}(l)
}
}
// checkLink function makes an HTTP request to the link parameter in order to check
// if the url is online and sends the link back to the main go routine.
func checkLink(link string, c chan string) {
_, err := http.Get(link)
if err != nil {
fmt.Println(link, "might be down!")
// sending a message back to the main go routine
c <- link
return
}
fmt.Println(link, "is up!")
// sending a message back to the main go routine
c <- link
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment