Skip to content

Instantly share code, notes, and snippets.

@lcaballero
Last active June 5, 2016 08:25
Show Gist options
  • Save lcaballero/c8f78321bf849fda9f57e47d974f3223 to your computer and use it in GitHub Desktop.
Save lcaballero/c8f78321bf849fda9f57e47d974f3223 to your computer and use it in GitHub Desktop.
Tim's Question
package main
import (
"fmt"
"net/http"
"io/ioutil"
"time"
)
type QueryResponse struct {
Id int
Body string
Started time.Time
Finished time.Time
Error error
}
func main() {
size := 10
headroom := 1
res := make(chan *QueryResponse, size)
for i := 0; i < size - headroom; i++ {
fmt.Println("First: ", i)
go Query(i, res)
}
coll := make([]*QueryResponse, 0, size)
DONE:
for {
select {
case r := <-res:
fmt.Println("received: ", r.Id)
coll = append(coll, r)
if len(coll) == size {
fmt.Println("done got 5")
break DONE;
}
if len(coll) == (size - headroom) {
fmt.Println("Last 1")
go Query(size - 1, res)
}
continue
case <-time.After(300*time.Millisecond):
fmt.Println("done timed out.")
break DONE;
}
}
for _,c := range coll {
fmt.Println(c.Id)
}
}
func Query(id int, results chan *QueryResponse) {
started := time.Now()
if id == 3 {
<-time.After(400*time.Millisecond)
}
resp, err := http.Get("http://example.com/")
if err != nil {
results <- &QueryResponse{
Error:err,
Started:started,
Finished: time.Now(),
}
return
}
res, err := ioutil.ReadAll(resp.Body)
if err != nil {
results <- &QueryResponse{
Error:err,
Started:started,
Finished: time.Now(),
}
return
}
results <- &QueryResponse{
Id: id,
Body: string(res),
Error: nil,
Started: started,
Finished: time.Now(),
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment