Last active
June 14, 2018 17:42
-
-
Save bojand/2962a3241615fd5b31e67cf98e13e7e4 to your computer and use it in GitHub Desktop.
parallel data
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 ( | |
"encoding/json" | |
"fmt" | |
) | |
type User struct { | |
ID int `json:"id"` | |
Name string `json:"name"` | |
} | |
type UserRequest User | |
func Create(u *User) { | |
fmt.Printf("Create user: %+v\n", u) | |
} | |
func GetCount(countCh chan int) { | |
fmt.Println("GetCount") | |
countCh <- 2 | |
close(countCh) | |
} | |
func GetData(dataCh chan []*User) { | |
fmt.Println("GetData") | |
s := make([]*User, 0) | |
s = append(s, &User{ID: 123, Name: "Bob"}, &User{ID: 212, Name: "Kate"}) | |
dataCh <- s | |
close(dataCh) | |
} | |
type UserResponse struct { | |
Count int `json:"count"` | |
Data []*User `json:"data"` | |
} | |
func QueryUsers() (*UserResponse, error) { | |
countCh := make(chan int, 1) | |
dataCh := make(chan []*User, 1) | |
errCh := make(chan error, 2) | |
fmt.Println("going") | |
go func() { | |
count, err := GetCount() | |
errCh <- err | |
countCh <- count | |
close(countCh) | |
}() | |
go func() { | |
data, err := GetData() | |
errCh <- err | |
dataCh <- data | |
close(dataCh) | |
}() | |
fmt.Println("getting") | |
count, data, err1, err2 := <-countCh, <-dataCh, <-errCh, <-errCh | |
if err1 != nil { | |
return nil, err1 | |
} | |
if err2 != nil { | |
return nil, err2 | |
} | |
ur := &UserResponse{ | |
Count: count, | |
Data: data, | |
} | |
return ur, nil | |
} | |
func main() { | |
u := &UserRequest{ID: 1, Name: "Foo"} | |
Create((*User)(u)) | |
ur := QueryUsers() | |
str, _ := json.Marshal(ur) | |
fmt.Println(string(str)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment