Skip to content

Repository files navigation

bear: embeddable application router

Coverage status

API documentation

bear.Mux is an HTTP multiplexer. It uses a tree structure for fast routing, supports dynamic parameters, middleware, and accepts both native http.HandlerFunc or bear.HandlerFunc, which accepts an extra *Context argument that allows storing state (using the Get() and Set() methods) and calling the Next() middleware.

Install

go get -u github.com/ursiform/bear

Quick start

Create main.go in a new folder

package main
import (
"fmt""github.com/ursiform/bear""log""net/http"
)
funclogRequest(res http.ResponseWriter, req*http.Request, ctx*bear.Context) {
log.Printf("%s %s\n", req.Method, req.URL.Path)
ctx.Next()
}
funcnotFound(res http.ResponseWriter, req*http.Request, ctx*bear.Context) {
res.Header().Set("Content-Type", "text/plain")
res.WriteHeader(http.StatusNotFound)
res.Write([]byte("Sorry, not found!\n"))
}
funcone(res http.ResponseWriter, req*http.Request, ctx*bear.Context) {
ctx.Set("one", "set in func one").Next() // Set() allows chaining
}
functwo(res http.ResponseWriter, req*http.Request, ctx*bear.Context) {
ctx.Set("two", "set in func two").Next()
}
functhree(res http.ResponseWriter, req*http.Request, ctx*bear.Context) {
greet:=fmt.Sprintf("Hello, %s!\n", ctx.Params["user"])
first:=ctx.Get("one").(string) // assert type: interface{} as stringsecond:=ctx.Get("two").(string) // assert type: interface{} as stringstate:=fmt.Sprintf("state one: %s\nstate two: %s\n", first, second)
res.Header().Set("Content-Type", "text/plain")
res.Write([]byte(greet+state))
}
funcmain() {
mux:=bear.New()
mux.Always(logRequest) // log each incoming requestmux.On("GET", "/hello/{user}", one, two, three) // dynamic URL param {user}mux.On("*", "/*", notFound) // wildcard method + pathhttp.ListenAndServe(":1337", mux)
}

###Build and start a server

$ go build -o ./server && ./server

###Test using curl

$ curl http://localhost:1337/hello/world
Hello, world!
state one: set in func one
state two: set in func two
$ curl http://localhost:1337/hello/world/foo
Sorry, not found!

###Check server log output

2016/02/06 15:19:50 GET /hello/world
2016/02/06 15:20:00 GET /hello/world/foo

Test

go test -cover github.com/ursiform/bear

API

API documentation

License

MIT License

About

An HTTP multiplexer / middleware router for Go

Resources

Stars

16 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages