Skip to content

Instantly share code, notes, and snippets.

@reiddraper
Created December 27, 2010 17:49
Show Gist options
  • Save reiddraper/756350 to your computer and use it in GitHub Desktop.
Save reiddraper/756350 to your computer and use it in GitHub Desktop.
package main
import (
"http"
"net"
"io"
"log"
"os"
"bufio"
)
type application interface {
Route(s string) Handler
}
type handlerFunc func(io.Writer, *http.Request)
type Handler interface {
ServeHTTP(io.Writer, *http.Request)
}
func (f handlerFunc) ServeHTTP(w io.Writer, r *http.Request){
f(w, r)
}
type Application struct {
handlers map[string] Handler
}
func (a *Application) Route(s string) Handler {
if handler, ok := a.handlers[s]; ok {
return handler
}
return handlerFunc(helloHandler)
}
func (a *Application) Handle(s string, h Handler) {
a.handlers[s] = h
}
func helloHandler(w io.Writer, req *http.Request) {
io.WriteString(w, "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nhello")
}
func newConn(conn net.Conn) *bufio.ReadWriter {
br := bufio.NewReader(conn)
bw := bufio.NewWriter(conn)
return bufio.NewReadWriter(br, bw)
}
func serve(listener net.Listener, app application) os.Error {
for {
rw, e := listener.Accept()
if e != nil {
return e
}
conn := newConn(rw)
request, _ := http.ReadRequest(conn.Reader)
app.Route(request.URL.Path).ServeHTTP(conn.Writer, request)
//helloHandler(conn.Writer, request)
conn.Flush()
rw.Close()
}
panic("not reached")
}
func ServeApplication(app application, addr string) {
listener, err := net.Listen("tcp", addr)
if err != nil {
log.Exit("can't listen: ", err.String())
}
serve(listener, app)
}
func main() {
app := new(Application)
//app.Handle("/", handlerFunc(helloHandler))
ServeApplication(app, ":8000")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment