Skip to content

Commit

Permalink
Initial Commit
Browse files Browse the repository at this point in the history
  • Loading branch information
julienschmidt committed Nov 19, 2013
0 parents commit 37170e0
Show file tree
Hide file tree
Showing 5 changed files with 816 additions and 0 deletions.
24 changes: 24 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
Copyright (c) 2013 Julien Schmidt. All rights reserved.


Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* The names of the contributors may not be used to endorse or promote
products derived from this software without specific prior written
permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL JULIEN SCHMIDT BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
87 changes: 87 additions & 0 deletions router.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
// Copyright 2013 Julien Schmidt. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file.

// A radix tree based HTTP request router
package router

import (
"errors"
"net/http"
)

// HandlerFunc is a function that can be registered to a route to handle HTTP
// requests. Like http.HandlerFunc, but has a third parameter for the route
// parameters.
type HandlerFunc func(http.ResponseWriter, *http.Request, map[string]string)

// Router is a http.Handler which can be used to dispatch requests to different
// handler functions via configurable routes
type Router struct {
node

// Enables automatic redirection if the current route can't be matched but
// handler for the path with (without) the trailing slash exists.
// For example if a route for /foo exists but /foo/ is requested, the client
// would be redirected to /foo with http status code 301.
RedirectTrailingSlash bool

// Configurable handler func which is used when no matching route is found.
// Default is the NotFound func of this package
NotFound http.HandlerFunc

// Handler func to handle panics recovered from http handlers.
// It should be used to generate a error page and return the http error code
// "500 - Internal Server Error".
// The handler can be used to keep your server from crashing because of
// unrecovered panics.
PanicHandler func(http.ResponseWriter, *http.Request, interface{})
}

// Make sure the Router conforms with the http.Handler interface
var _ http.Handler = New()

// New returnes a new initialized Router.
// The router can be configured to also match the requested HTTP method or the
// requested Host.
func New() *Router {
return &Router{
RedirectTrailingSlash: true,
NotFound: http.NotFound,
}
}

// Add registers a new request handler to the given path.
func (r *Router) Add(path string, h HandlerFunc) error {
if path[0] != '/' {
return errors.New("Path must begin with /")
}
return r.addRoute(path, h)
}

// Make the router implement the http.Handler interface.
func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) {
if r.PanicHandler != nil {
defer func() {
if rcv := recover(); rcv != nil {
r.PanicHandler(w, req, rcv)
}
}()
}

path := req.URL.Path

if handle, vars, tsr := r.getValue(path); handle != nil {
handle(w, req, vars)
} else if tsr && r.RedirectTrailingSlash {
if path[len(path)-1] == '/' {
http.Redirect(w, req, path[:len(path)-1], http.StatusMovedPermanently)
return
} else {
http.Redirect(w, req, path+"/", http.StatusMovedPermanently)
return
}
} else { // Handle 404
r.NotFound(w, req)
}
}
49 changes: 49 additions & 0 deletions router_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
// Copyright 2013 Julien Schmidt. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file.

package router

import (
"net/http"
"reflect"
"testing"
)

type mockResponseWriter struct{}

func (m *mockResponseWriter) Header() (h http.Header) {
return http.Header{}
}

func (m *mockResponseWriter) Write(p []byte) (n int, err error) {
return len(p), nil
}

func (m *mockResponseWriter) WriteString(s string) (n int, err error) {
return len(s), nil
}

func (m *mockResponseWriter) WriteHeader(int) {}

func TestRouter(t *testing.T) {
router := New()

routed := false
router.Add("/user/:name", func(w http.ResponseWriter, r *http.Request, vars map[string]string) {
routed = true
want := map[string]string{"name": "gopher"}
if !reflect.DeepEqual(vars, want) {
t.Fatalf("Wrong wildcard values: want %v, got %v", want, vars)
}
})

w := new(mockResponseWriter)

req, _ := http.NewRequest("GET", "/user/gopher", nil)
router.ServeHTTP(w, req)

if !routed {
t.Fatal("Routing failed")
}
}
Loading

0 comments on commit 37170e0

Please sign in to comment.