Skip to content

Instantly share code, notes, and snippets.

@MehdiZonjy
Created August 5, 2018 12:04
Show Gist options
  • Save MehdiZonjy/aeaa3f8c5c3e91aba873ddd234584b3c to your computer and use it in GitHub Desktop.
Save MehdiZonjy/aeaa3f8c5c3e91aba873ddd234584b3c to your computer and use it in GitHub Desktop.
async calls in go using channels
package main
import (
"fmt"
"io/ioutil"
"net/http"
)
type Message struct {
Error error
Result string
}
func getURL(url string) chan Message {
ch := make(chan Message)
sendError := func(err error) {
ch <- Message{
Result: "",
Error: err}
}
go func() {
defer close(ch)
result, err := http.Get(url)
if err != nil {
sendError(err)
return
}
defer result.Body.Close()
bytes, err := ioutil.ReadAll(result.Body)
if err != nil {
sendError(err)
return
}
ch <- Message{
Error: err,
Result: string(bytes)}
}()
return ch
}
func main() {
ch1 := getURL("https://jsonplaceholder.typicode.com/posts/2")
ch2 := getURL("https://jsonplaceholder.typicode.com/posts/1")
result1 := <-ch1
result2 := <-ch2
if result1.Error != nil || result2.Error != nil {
fmt.Println("Failed to perform fetch")
fmt.Printf("Error1 %v \n", result1.Error)
fmt.Printf("Error2 %v \n", result2.Error)
return
}
fmt.Printf("result1 %v \n", result1.Result)
fmt.Printf("result2 %v \n", result2.Result)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment