Skip to content

Instantly share code, notes, and snippets.

@soareschen
Last active August 29, 2015 14:07
Show Gist options
  • Save soareschen/334af104bc7566666605 to your computer and use it in GitHub Desktop.
Save soareschen/334af104bc7566666605 to your computer and use it in GitHub Desktop.
First try of using Go in Quiver-style
package main
import (
"fmt"
"time"
"net/http"
)
type handlerFunction func(
res http.ResponseWriter,
req *http.Request)
/*
* This is a placeholder struct that wraps around
* a raw function of the same signature so that
* we can specify the ServeHTTP
* method that satisfy the http.Handler interface
*/
type HttpHandler struct {
handleHttp handlerFunction
}
func (handler HttpHandler) ServeHTTP(
res http.ResponseWriter,
req *http.Request) {
handler.handleHttp(res, req)
}
/*
* Convert a handler function with the same signature into
* HttpHandler struct that wraps around the raw function
*/
func HandlerFunc(handler handlerFunction) HttpHandler {
return HttpHandler{handler}
}
/*
* Converts a function that return a channel
* simulating string stream into a HttpHandler
*/
func stringChannelHandler(handler func() <-chan string) HttpHandler {
return HandlerFunc(
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