Skip to content

Instantly share code, notes, and snippets.

@picatz
Created August 21, 2018 17:51
Show Gist options
  • Save picatz/3cf096c9c1ffe9b34360ec46f393c08f to your computer and use it in GitHub Desktop.
Save picatz/3cf096c9c1ffe9b34360ec46f393c08f to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"log"
"net/http"
"time"
)
func newProducer(readTimeout time.Duration, products ...string) <-chan string {
results := make(chan string)
go func() {
defer close(results)
for _, product := range products {
select {
case results <- product:
// didn't time out
case <-time.After(readTimeout):
return
}
}
}()
return results
}
var timeout = 1 * time.Second
func exampleEndpoint(w http.ResponseWriter, req *http.Request) {
var counter = 0
for result := range newProducer(timeout, "A", "B", "C", "E", "F", "G") {
counter++
fmt.Fprintln(w, result)
if counter == 3 {
return
}
}
}
func main() {
http.HandleFunc("/example", exampleEndpoint)
log.Fatal(http.ListenAndServe(":8080", nil))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment