Last active
December 3, 2020 22:18
-
-
Save bagus2x/8be266d711c5d4347d000e726bde67f1 to your computer and use it in GitHub Desktop.
belajar handle error di goroutine dengan channel
This file contains 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 result struct { | |
data string | |
err error | |
} | |
func main() { | |
c1 := make(chan result) | |
c2 := make(chan result) | |
go getTodos(c1) | |
go getPosts(c2) | |
for i := 0; i < 2; i++ { | |
select { | |
case todos := <-c1: | |
fmt.Println(todos) | |
case posts := <-c2: | |
fmt.Println(posts) | |
} | |
} | |
} | |
func getTodos(data chan<- result) { | |
resp, err := http.Get("https://jsonplaceholder.typicode.com/todos") | |
if err != nil { | |
data <- result{err: err} | |
return | |
} | |
str, err := ioutil.ReadAll(resp.Body) | |
if err != nil { | |
data <- result{err: err} | |
return | |
} | |
data <- result{string(str), nil} | |
} | |
func getPosts(data chan<- result) { | |
resp, err := http.Get("https://jsonplaceholder.typicode.com/posts") | |
if err != nil { | |
data <- result{err: err} | |
return | |
} | |
str, err := ioutil.ReadAll(resp.Body) | |
if err != nil { | |
data <- result{err: err} | |
return | |
} | |
data <- result{string(str), nil} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment