Created
August 21, 2018 17:51
-
-
Save picatz/3cf096c9c1ffe9b34360ec46f393c08f to your computer and use it in GitHub Desktop.
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" | |
"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