Skip to content

Instantly share code, notes, and snippets.

@laktek
Last active August 29, 2015 14:07
Show Gist options
  • Save laktek/74a531d841e4d5c340f0 to your computer and use it in GitHub Desktop.
Save laktek/74a531d841e4d5c340f0 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"net/http"
"time"
)
/*
* Converts a function that return a channel
* simulating string stream into a HttpHandler
*/
func stringChannelHandler(handler func() <-chan string) http.HandlerFunc {
return func(res http.ResponseWriter, req *http.Request) {
for buf := range handler() {
fmt.Fprint(res, buf)
}
}
}
/*
* Create a HTTP handler that greet with the
* name provided. To simulate stream the
* base handler function return a channel
* that first sends the string "hello" then
* sleep for one second before sending the
* saved name string.
*/
func createGreeter(name string) http.Handler {
var handler = func() <-chan string {
channel := make(chan string)
go func() {
channel <- "Hello, "
time.Sleep(time.Second)
channel <- name
close(channel)
}()
return channel
}
return stringChannelHandler(handler)
}
/*
* Create a HTTP server that serves the string "Hello, Go"
* With the string "Go" written only after one second
*/
func main() {
var handler = createGreeter("Go")
http.ListenAndServe("localhost:8080", handler)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment