Skip to content

Instantly share code, notes, and snippets.

@hkolbeck
Forked from reiddraper/server.go
Created December 27, 2010 07:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hkolbeck/755948 to your computer and use it in GitHub Desktop.
Save hkolbeck/755948 to your computer and use it in GitHub Desktop.
package main
import (
"http"
"net"
"io"
"log"
"os"
"bufio"
)
type application interface {
Route(s string)
}
type handlerFunc func(io.Writer, *http.Request)
type Application struct {
handlers map[string] handlerFunc
}
func (a *Application) Route(s string) handlerFunc {
if handler, ok := a.handlers[s]; ok {
return handler
}
return helloHandler
}
func (a *Application) Handle(s string, h handlerFunc) {
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 {
return bufio.NewReadWriter(conn, conn)
}
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))(conn, request)
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() {
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment