-
-
Save hkolbeck/755948 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 ( | |
"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