go-playground/lars is tracked by TopGit as an open-source project, with 384 stars on GitHub, written primarily in Go. :rotating_light: Is a lightweight, fast and extensible zero allocation HTTP router for Go used to create customizable frameworks.
Snapshot summary built from the project's own GitHub metadata — there's no written TopGit review yet. The page will update automatically when a full review is published.
WHY NO REVIEW YET
TopGit writes full reviews for the most-starred, most-requested repositories. This page is a snapshot until then — see the READ ME tab for the original README in full.
LARS is a fast radix-tree based, zero allocation, HTTP router for Go. view examples. If looking for a more pure Go solution, be sure to check out pure which is essentially a pure version of lars
Why Another HTTP Router?
Have you ever been painted into a corner by a framework, ya me too! and I've noticed that allot of routers out there, IMHO, are adding so much functionality that they are turning into Web Frameworks, (which is fine, frameworks are important) however, not at the expense of flexibility and configurability. So with no further ado, introducing LARS an HTTP router that can be your launching pad in creating a framework for your needs. How? Context is an interface see example here, where you can add as little or much as you want or need and most importantly...under your control.
Key & Unique Features
Context is an interface - this allows passing of framework/globals/application specific variables. example
Smart Route Logic - helpful logic to help prevent adding bad routes, keeping your url's consistent. i.e. /user/:id and /user/:user_id - the second one will fail to add letting you know that :user_id should be :id
Uber simple middleware + handlers - middleware and handlers actually have the exact same definition!
Custom Handlers - can register custom handlers for making other middleware + handler patterns usable with this router; the best part about this is can register one for your custom context and not have to do type casting everywhere see here
Diverse handler support - Full support for standard/native http Handler + HandlerFunc + some others see here
When Parsing a form call Context's ParseForm amd ParseMulipartForm functions and the URL params will be added into the Form object, just like query parameters are, so no extra work
Fast & Efficient - lars uses a custom version of httprouter so incredibly fast and efficient.
Installation
go get -u github.com/go-playground/lars
Usage
Below is a simple example, for a full example see here
package main
import (
"fmt"
"net/http"
"github.com/go-playground/lars"
mw "github.com/go-playground/lars/_examples/middleware/logging-recovery"
)
func main() {
l := lars.New()
// LoggingAndRecovery is just an example copy paste and modify to your needs
l.Use(mw.LoggingAndRecovery)
l.Get("/", HelloWorld)
http.ListenAndServe(":3007", l.Serve())
}
// HelloWorld ...
func HelloWorld(c lars.Context) {
c.Response().Write([]byte("Hello World"))
// this will also work, Response() complies with http.ResponseWriter interface
fmt.Fprint(c.Response(), "Hello World")
}
URL Params
l := l.New()
// the matching param will be stored in the Context's params with name "id"
l.Get("/user/:id", UserHandler)
// serve css, js etc.. c.Param(lars.WildcardParam) will return the remaining path if
// you need to use it in a custom handler...
l.Get("/static/*", http.StripPrefix("/static/", http.FileServer(http.Dir("static"))))
...
Note: Since this router has only explicit matches, you can not register static routes and parameters for the same path segment. For example you can not register the patterns /user/new and /user/:user for the same request method at the same time. The routing of different request methods is independent from each other. I was initially against this, and this router allowed it in a previous version, however it nearly cost me in a big app where the dynamic param value say :type actually could have matched another static route and that's just too dangerous, so it is no longer allowed.
Groups
l.Use(LoggingAndRecovery)
...
l.Post("/users/add", ...)
// creates a group for user + inherits all middleware registered using l.Use()
user := l.Group("/user/:userid")
user.Get("", ...)
user.Post("", ...)
user.Delete("/delete", ...)
contactInfo := user.Group("/contact-info/:ciid")
contactinfo.Delete("/delete", ...)
// creates a group for others + inherits all middleware registered using l.Use() + adds
// OtherHandler to middleware
others := l.GroupWithMore("/others", OtherHandler)
// creates a group for admin WITH NO MIDDLEWARE... more can be added using admin.Use()
admin := l.GroupWithNone("/admin")
admin.Use(SomeAdminSecurityMiddleware)
...
Custom Context + Avoid Type Casting / Custom Handlers
...
// MyContext is a custom context
type MyContext struct {
*lars.Ctx // a little dash of Duck Typing....
}
// CustomContextFunction is a function that is specific to your applications needs that you added
func (mc *MyContext) CustomContextFunction() {
// do something
}
// newContext is the function that creates your custom context +
// contains lars's default context
func newContext(l *lars.LARS) lars.Context {
return &MyContext{
Ctx: lars.NewContext(l),
}
}
// casts custom context and calls you custom handler so you don;t have to type cast lars.Context everywhere
func castCustomContext(c lars.Context, handler lars.Handler) {
// could do it in all one statement, but in long form for readability
h := handler.(func(*MyContext))
ctx := c.(*MyContext)
h(ctx)
}
func main() {
l := lars.New()
l.RegisterContext(newContext) // all gets cached in pools for you
l.RegisterCustomHandler(func(*MyContext) {}, castCustomContext)
l.Use(Logger)
l.Get("/", Home)
http.ListenAndServe(":3007", l.Serve())
}
// Home ...notice the receiver is *MyContext, castCustomContext handled the type casting for us
// quite the time saver if you ask me.
func Home(c *MyContext) {
c.CustomContextFunction()
...
}
Decoding Body
For full example see here.
currently JSON, XML, FORM + Multipart Form's are support out of the box.
// first argument denotes yes or no I would like URL query parameter fields
// to be included. i.e. 'id' in route '/user/:id' should it be included.
// run, then change to false and you'll see user.ID is not populated.
if err := c.Decode(true, maxBytes, &user); err != nil {
log.Println(err)
}
Misc
...
// can register multiple handlers, the last is considered the last in the chain and others
// considered middleware, but just for this route and not added to middleware like l.Use() does.
l.Get(/"home", AdditionalHandler, HomeHandler)
// set custom 404 ( not Found ) handler
l.Register404(404Handler)
// Redirect to or from ending slash if route not found, default is true
l.SetRedirectTrailingSlash(true)
// Handle 405 ( Method Not allowed ), default is false
l.SetHandle405MethodNotAllowed(false)
// automatically handle OPTION requests; manually configured
// OPTION handlers take precedence. default true
l.SetAutomaticallyHandleOPTIONS(set bool)
// register custom context
l.RegisterContext(ContextFunc)
// Register custom handler type, see https://github.com/go-playground/lars/blob/master/util.go#L62
// for example handler creation
l.RegisterCustomHandler(interface{}, CustomHandlerFunc)
// NativeChainHandler is used as a helper to create your own custom handlers, or use custom handlers
// that already exist an example usage can be found here
// https://github.com/go-playground/lars/blob/master/util.go#L86, below is an example using nosurf CSRF middleware
l.Use(nosurf.NewPure(lars.NativeChainHandler))
// Context has 2 methods of which you should be aware of ParseForm and ParseMulipartForm, they just call the
// default http functions but provide one more additional feature, they copy the URL params to the request
// Forms variables, just like Query parameters would have been.
// The functions are for convenience and are totally optional.
Special Note
I don't know if it was an oversight or just an assumption about how middleware would be used with Go 1.7's new
context integration into the *http.Request but there are a few quirks. As you know lars handles multiple handler
types, including the native handler, this functionality is possible because of the way lar handles the middleware; lars
does not chain the middleware in the normal way, but rather calles each in sequence; because of this all you have to
do is call c.Next() or it has already been wrapped to do so for you transparently. OK getting back to the point, if you
are not using lars.Context to set the context information you will have to set the request object so that the information
gets back to the calling package. eg.
// because 'r' is a copy of a pointer to allow the information to get
// back to the caller, need to set the value of 'r' as below with '*r'
func(w http.ResponseWriter, r *http.Request) {
*r = *r.WithContext(context.WithValue(r.Context(), 0, "testval1"))
}
this is not an issue specific to lars, but a quirk of the way context is tied to the http.Request object.
Middleware
There are some pre-defined middlewares within the middleware folder; NOTE: that the middleware inside will
comply with the following rule(s):
Are completely reusable by the community without modification
Other middleware will be listed under the _examples/middleware/... folder for a quick copy/paste modify. as an example a logging or
recovery middleware are very application dependent and therefore will be listed under the _examples/middleware/...
Benchmarks
Run on MacBook Pro (15-inch, 2017) 3.1 GHz Intel Core i7 16GB DDR3 using Go version go1.9.2 darwin/amd64
NOTICE: lars uses a custom version of httprouter, benchmarks can be found here
I'm jumping on the vendoring bandwagon, you should vendor this package as I will not
be creating different version with gopkg.in like allot of my other libraries.
Why? because my time is spread pretty thin maintaining all of the libraries I have + LIFE,
it is so freeing not to worry about it and will help me keep pouring out bigger and better
things for you the community.
This package is inspired by the following
httptreemux
httprouter
echo
gin
Licenses
MIT License (MIT), Copyright (c) 2015 Dean Karn
BSD License, Copyright (c) 2013 Julien Schmidt. All rights reserved.
No homepage URL was recorded for go-playground/lars in TopGit's last sync. The README tab above frequently contains screenshots and demo links, or check the repository description on GitHub.
How active is development on go-playground/lars?
The most recent commit recorded on go-playground/lars was 7.5 years ago, based on the GitHub push timestamp. The repository has 23 forks — one of the better signals of community interest.
How many stars does go-playground/lars have?
go-playground/lars has 384 GitHub stars — refresh the page for the live number, or check github.com/go-playground/lars. TopGit mirrors GitHub's count but does not claim minute-by-minute accuracy.
What language is go-playground/lars written in?
go-playground/lars is written primarily in Go. GitHub's language field is based on the largest share of bytes in the default branch.
What license does go-playground/lars use?
go-playground/lars is released under the MIT license. Always verify the LICENSE file directly on GitHub for the authoritative terms — license strings can be edited out of sync with a project's actual stance.
What topics is go-playground/lars associated with?
GitHub's repository topics for go-playground/lars: "customizable-context", "http-router", "zero-allocation". TopGit's editorial category is open-source.
Where do I read more about go-playground/lars?
This TopGit page is a snapshot — the READ ME tab shows the project's own README content (links stripped, images preserved). The GitHub repository at github.com/go-playground/lars is the definitive source.
Read full README in the tab above.
Still deciding about lars?
One click hands the question to an AI along with this page — see what it says about lars.