Created
August 5, 2018 12:04
-
-
Save MehdiZonjy/aeaa3f8c5c3e91aba873ddd234584b3c to your computer and use it in GitHub Desktop.
async calls in go using channels
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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