Top Related Projects
Package gorilla/mux is a powerful HTTP router and URL matcher for building Go web servers with 🦍
Gin is a HTTP web framework written in Go (Golang). It features a Martini-like API with much better performance -- up to 40 times faster. If you need smashing performance, get yourself some Gin.
High performance, minimalist Go web framework
lightweight, idiomatic and composable router for building Go HTTP services
⚡️ Express inspired web framework written in Go
Fast HTTP package for Go. Tuned for high performance. Zero memory allocations in hot paths. Up to 10x faster than net/http
Quick Overview
julienschmidt/httprouter is a lightweight and high-performance HTTP request router for Go. It's designed to be fast and memory-efficient, making it an excellent choice for building RESTful APIs and web services. The router supports URL parameters and is compatible with the standard http.Handler
interface.
Pros
- Extremely fast and efficient routing
- Low memory footprint
- Easy to use and integrate with existing Go web applications
- Supports URL parameters and wildcards
Cons
- Limited built-in middleware support
- No built-in support for route groups
- May require additional libraries for more complex routing scenarios
- Less feature-rich compared to some other routing libraries
Code Examples
- Basic routing:
package main
import (
"fmt"
"github.com/julienschmidt/httprouter"
"net/http"
"log"
)
func Index(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
fmt.Fprint(w, "Welcome!\n")
}
func main() {
router := httprouter.New()
router.GET("/", Index)
log.Fatal(http.ListenAndServe(":8080", router))
}
- URL parameters:
func UserProfile(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
fmt.Fprintf(w, "User profile: %s\n", ps.ByName("name"))
}
router.GET("/user/:name", UserProfile)
- Serving static files:
router.ServeFiles("/static/*filepath", http.Dir("static"))
Getting Started
To use httprouter in your Go project, follow these steps:
-
Install the package:
go get github.com/julienschmidt/httprouter
-
Import the package in your Go code:
import "github.com/julienschmidt/httprouter"
-
Create a new router and define your routes:
router := httprouter.New() router.GET("/", Index) router.POST("/api/data", CreateData)
-
Start the server with your router:
log.Fatal(http.ListenAndServe(":8080", router))
Competitor Comparisons
Package gorilla/mux is a powerful HTTP router and URL matcher for building Go web servers with 🦍
Pros of mux
- More feature-rich, offering middleware, subrouters, and custom matchers
- Supports URL path variables with custom regular expressions
- Allows for flexible route matching based on headers, query parameters, etc.
Cons of mux
- Generally slower performance compared to httprouter
- Higher memory usage due to its more complex routing structure
- Steeper learning curve for beginners due to additional features
Code Comparison
mux:
r := mux.NewRouter()
r.HandleFunc("/users/{id:[0-9]+}", UserHandler).Methods("GET")
r.HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler).Methods("GET")
http.ListenAndServe(":8080", r)
httprouter:
router := httprouter.New()
router.GET("/users/:id", UserHandler)
router.GET("/articles/:category/:id", ArticleHandler)
http.ListenAndServe(":8080", router)
Both mux and httprouter are popular routing libraries for Go, each with its own strengths. mux offers more flexibility and features, making it suitable for complex applications, while httprouter focuses on simplicity and performance, making it ideal for high-performance, straightforward routing needs.
Gin is a HTTP web framework written in Go (Golang). It features a Martini-like API with much better performance -- up to 40 times faster. If you need smashing performance, get yourself some Gin.
Pros of Gin
- More feature-rich, offering middleware support, JSON validation, and error management
- Better performance in high-load scenarios due to its radix tree-based routing
- Extensive documentation and larger community support
Cons of Gin
- Larger codebase and more dependencies, potentially increasing complexity
- Steeper learning curve for beginners compared to HttpRouter's simplicity
- May be overkill for simple API projects where HttpRouter would suffice
Code Comparison
HttpRouter:
router := httprouter.New()
router.GET("/user/:name", func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
fmt.Fprintf(w, "Hello, %s!", ps.ByName("name"))
})
Gin:
router := gin.Default()
router.GET("/user/:name", func(c *gin.Context) {
name := c.Param("name")
c.String(http.StatusOK, "Hello, %s!", name)
})
Both frameworks offer similar routing capabilities, but Gin provides a more context-aware approach with its gin.Context
object, which encapsulates HTTP request and response handling.
High performance, minimalist Go web framework
Pros of Echo
- Full-featured web framework with middleware, templating, and data binding
- Built-in support for WebSocket and HTTP/2
- More extensive documentation and larger community
Cons of Echo
- Higher memory usage and slightly slower performance
- Steeper learning curve due to more features and complexity
- Less flexibility for custom routing implementations
Code Comparison
Echo:
e := echo.New()
e.GET("/users/:id", func(c echo.Context) error {
id := c.Param("id")
return c.String(http.StatusOK, id)
})
HttpRouter:
router := httprouter.New()
router.GET("/users/:id", func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
id := ps.ByName("id")
fmt.Fprint(w, id)
})
Summary
Echo is a more comprehensive web framework with additional features, while HttpRouter focuses on high-performance routing. Echo offers a wider range of built-in functionality, making it suitable for larger applications. HttpRouter, on the other hand, provides a lightweight and fast routing solution, ideal for projects that require minimal overhead and maximum performance. The choice between the two depends on the specific needs of your project, balancing features against performance and simplicity.
lightweight, idiomatic and composable router for building Go HTTP services
Pros of chi
- More feature-rich with middleware support and sub-routing
- Follows standard http.Handler interface, making it more idiomatic
- Offers a wider range of utility functions for common HTTP operations
Cons of chi
- Slightly slower performance compared to httprouter
- More complex API, which may have a steeper learning curve
- Larger codebase and memory footprint
Code Comparison
chi:
r := chi.NewRouter()
r.Get("/user/{id}", func(w http.ResponseWriter, r *http.Request) {
id := chi.URLParam(r, "id")
// Handle request
})
httprouter:
router := httprouter.New()
router.GET("/user/:id", func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
id := ps.ByName("id")
// Handle request
})
Both chi and httprouter are popular Go HTTP routers, each with its own strengths. chi offers more features and follows Go's standard library patterns, making it easier to integrate with existing code. However, httprouter provides better performance and a simpler API, which may be preferable for projects with straightforward routing needs. The choice between the two depends on the specific requirements of your project, balancing features, performance, and ease of use.
⚡️ Express inspired web framework written in Go
Pros of Fiber
- Higher-level framework with more built-in features (middleware, templating, etc.)
- Express-like syntax, familiar to Node.js developers
- Better performance in high-concurrency scenarios
Cons of Fiber
- Larger codebase and more dependencies
- Steeper learning curve for Go beginners
- Less flexibility for custom routing implementations
Code Comparison
Fiber:
app := fiber.New()
app.Get("/user/:name", func(c *fiber.Ctx) error {
return c.SendString("Hello, " + c.Params("name"))
})
app.Listen(":3000")
Httprouter:
router := httprouter.New()
router.GET("/user/:name", func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
fmt.Fprintf(w, "Hello, %s", ps.ByName("name"))
})
http.ListenAndServe(":3000", router)
Summary
Fiber is a more feature-rich framework with Express-like syntax, offering better performance in high-concurrency scenarios. However, it has a larger codebase and a steeper learning curve. Httprouter is a lightweight, fast HTTP router with a simpler API, making it easier for Go beginners to understand and use. The choice between the two depends on project requirements, team expertise, and performance needs.
Fast HTTP package for Go. Tuned for high performance. Zero memory allocations in hot paths. Up to 10x faster than net/http
Pros of fasthttp
- Significantly higher performance and lower memory usage
- Built-in support for connection pooling and reuse
- Provides both client and server implementations
Cons of fasthttp
- Not compatible with net/http standard library
- Less mature ecosystem and community support
- May require more manual handling of certain HTTP features
Code Comparison
httprouter:
router := httprouter.New()
router.GET("/", Index)
router.GET("/hello/:name", Hello)
log.Fatal(http.ListenAndServe(":8080", router))
fasthttp:
requestHandler := func(ctx *fasthttp.RequestCtx) {
switch string(ctx.Path()) {
case "/":
fmt.Fprintf(ctx, "Welcome!")
case "/hello":
fmt.Fprintf(ctx, "Hello, %s!", ctx.QueryArgs().Peek("name"))
}
}
log.Fatal(fasthttp.ListenAndServe(":8080", requestHandler))
Key Differences
- httprouter focuses on routing, while fasthttp is a complete HTTP implementation
- httprouter uses standard net/http interfaces, fasthttp has its own API
- fasthttp requires more manual handling of request parsing and response writing
- httprouter provides built-in support for path parameters, fasthttp requires manual parsing
Use Cases
- httprouter: Standard web applications, RESTful APIs, projects requiring net/http compatibility
- fasthttp: High-performance applications, microservices, scenarios where raw speed is critical
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
HttpRouter
HttpRouter is a lightweight high performance HTTP request router (also called multiplexer or just mux for short) for Go.
In contrast to the default mux of Go's net/http
package, this router supports variables in the routing pattern and matches against the request method. It also scales better.
The router is optimized for high performance and a small memory footprint. It scales well even with very long paths and a large number of routes. A compressing dynamic trie (radix tree) structure is used for efficient matching.
Features
Only explicit matches: With other routers, like http.ServeMux
, a requested URL path could match multiple patterns. Therefore they have some awkward pattern priority rules, like longest match or first registered, first matched. By design of this router, a request can only match exactly one or no route. As a result, there are also no unintended matches, which makes it great for SEO and improves the user experience.
Stop caring about trailing slashes: Choose the URL style you like, the router automatically redirects the client if a trailing slash is missing or if there is one extra. Of course it only does so, if the new path has a handler. If you don't like it, you can turn off this behavior.
Path auto-correction: Besides detecting the missing or additional trailing slash at no extra cost, the router can also fix wrong cases and remove superfluous path elements (like ../
or //
). Is CAPTAIN CAPS LOCK one of your users? HttpRouter can help him by making a case-insensitive look-up and redirecting him to the correct URL.
Parameters in your routing pattern: Stop parsing the requested URL path, just give the path segment a name and the router delivers the dynamic value to you. Because of the design of the router, path parameters are very cheap.
Zero Garbage: The matching and dispatching process generates zero bytes of garbage. The only heap allocations that are made are building the slice of the key-value pairs for path parameters, and building new context and request objects (the latter only in the standard Handler
/HandlerFunc
API). In the 3-argument API, if the request path contains no parameters not a single heap allocation is necessary.
Best Performance: Benchmarks speak for themselves. See below for technical details of the implementation.
No more server crashes: You can set a Panic handler to deal with panics occurring during handling a HTTP request. The router then recovers and lets the PanicHandler
log what happened and deliver a nice error page.
Perfect for APIs: The router design encourages to build sensible, hierarchical RESTful APIs. Moreover it has built-in native support for OPTIONS requests and 405 Method Not Allowed
replies.
Of course you can also set custom NotFound
and MethodNotAllowed
handlers and serve static files.
Usage
This is just a quick introduction, view the Docs for details.
$ go get github.com/julienschmidt/httprouter
and use it, like in this trivial example:
package main
import (
"fmt"
"net/http"
"log"
"github.com/julienschmidt/httprouter"
)
func Index(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
fmt.Fprint(w, "Welcome!\n")
}
func Hello(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
fmt.Fprintf(w, "hello, %s!\n", ps.ByName("name"))
}
func main() {
router := httprouter.New()
router.GET("/", Index)
router.GET("/hello/:name", Hello)
log.Fatal(http.ListenAndServe(":8080", router))
}
Named parameters
As you can see, :name
is a named parameter. The values are accessible via httprouter.Params
, which is just a slice of httprouter.Param
s. You can get the value of a parameter either by its index in the slice, or by using the ByName(name)
method: :name
can be retrieved by ByName("name")
.
When using a http.Handler
(using router.Handler
or http.HandlerFunc
) instead of HttpRouter's handle API using a 3rd function parameter, the named parameters are stored in the request.Context
. See more below under Why doesn't this work with http.Handler?.
Named parameters only match a single path segment:
Pattern: /user/:user
/user/gordon match
/user/you match
/user/gordon/profile no match
/user/ no match
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.
Catch-All parameters
The second type are catch-all parameters and have the form *name
. Like the name suggests, they match everything. Therefore they must always be at the end of the pattern:
Pattern: /src/*filepath
/src/ match
/src/somefile.go match
/src/subdir/somefile.go match
How does it work?
The router relies on a tree structure which makes heavy use of common prefixes, it is basically a compact prefix tree (or just Radix tree). Nodes with a common prefix also share a common parent. Here is a short example what the routing tree for the GET
request method could look like:
Priority Path Handle
9 \ *<1>
3 âs nil
2 |âearch\ *<2>
1 |âupport\ *<3>
2 âblog\ *<4>
1 | â:post nil
1 | â\ *<5>
2 âabout-us\ *<6>
1 | âteam\ *<7>
1 âcontact\ *<8>
Every *<num>
represents the memory address of a handler function (a pointer). If you follow a path trough the tree from the root to the leaf, you get the complete route path, e.g \blog\:post\
, where :post
is just a placeholder (parameter) for an actual post name. Unlike hash-maps, a tree structure also allows us to use dynamic parts like the :post
parameter, since we actually match against the routing patterns instead of just comparing hashes. As benchmarks show, this works very well and efficient.
Since URL paths have a hierarchical structure and make use only of a limited set of characters (byte values), it is very likely that there are a lot of common prefixes. This allows us to easily reduce the routing into ever smaller problems. Moreover the router manages a separate tree for every request method. For one thing it is more space efficient than holding a method->handle map in every single node, it also allows us to greatly reduce the routing problem before even starting the look-up in the prefix-tree.
For even better scalability, the child nodes on each tree level are ordered by priority, where the priority is just the number of handles registered in sub nodes (children, grandchildren, and so on..). This helps in two ways:
- Nodes which are part of the most routing paths are evaluated first. This helps to make as much routes as possible to be reachable as fast as possible.
- It is some sort of cost compensation. The longest reachable path (highest cost) can always be evaluated first. The following scheme visualizes the tree structure. Nodes are evaluated from top to bottom and from left to right.
â------------
â---------
â-----
â----
â--
â--
â-
Why doesn't this work with http.Handler
?
It does! The router itself implements the http.Handler
interface. Moreover the router provides convenient adapters for http.Handler
s and http.HandlerFunc
s which allows them to be used as a httprouter.Handle
when registering a route.
Named parameters can be accessed request.Context
:
func Hello(w http.ResponseWriter, r *http.Request) {
params := httprouter.ParamsFromContext(r.Context())
fmt.Fprintf(w, "hello, %s!\n", params.ByName("name"))
}
Alternatively, one can also use params := r.Context().Value(httprouter.ParamsKey)
instead of the helper function.
Just try it out for yourself, the usage of HttpRouter is very straightforward. The package is compact and minimalistic, but also probably one of the easiest routers to set up.
Automatic OPTIONS responses and CORS
One might wish to modify automatic responses to OPTIONS requests, e.g. to support CORS preflight requests or to set other headers.
This can be achieved using the Router.GlobalOPTIONS
handler:
router.GlobalOPTIONS = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("Access-Control-Request-Method") != "" {
// Set CORS headers
header := w.Header()
header.Set("Access-Control-Allow-Methods", header.Get("Allow"))
header.Set("Access-Control-Allow-Origin", "*")
}
// Adjust status code to 204
w.WriteHeader(http.StatusNoContent)
})
Where can I find Middleware X?
This package just provides a very efficient request router with a few extra features. The router is just a http.Handler
, you can chain any http.Handler compatible middleware before the router, for example the Gorilla handlers. Or you could just write your own, it's very easy!
Alternatively, you could try a web framework based on HttpRouter.
Multi-domain / Sub-domains
Here is a quick example: Does your server serve multiple domains / hosts? You want to use sub-domains? Define a router per host!
// We need an object that implements the http.Handler interface.
// Therefore we need a type for which we implement the ServeHTTP method.
// We just use a map here, in which we map host names (with port) to http.Handlers
type HostSwitch map[string]http.Handler
// Implement the ServeHTTP method on our new type
func (hs HostSwitch) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// Check if a http.Handler is registered for the given host.
// If yes, use it to handle the request.
if handler := hs[r.Host]; handler != nil {
handler.ServeHTTP(w, r)
} else {
// Handle host names for which no handler is registered
http.Error(w, "Forbidden", 403) // Or Redirect?
}
}
func main() {
// Initialize a router as usual
router := httprouter.New()
router.GET("/", Index)
router.GET("/hello/:name", Hello)
// Make a new HostSwitch and insert the router (our http handler)
// for example.com and port 12345
hs := make(HostSwitch)
hs["example.com:12345"] = router
// Use the HostSwitch to listen and serve on port 12345
log.Fatal(http.ListenAndServe(":12345", hs))
}
Basic Authentication
Another quick example: Basic Authentication (RFC 2617) for handles:
package main
import (
"fmt"
"log"
"net/http"
"github.com/julienschmidt/httprouter"
)
func BasicAuth(h httprouter.Handle, requiredUser, requiredPassword string) httprouter.Handle {
return func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
// Get the Basic Authentication credentials
user, password, hasAuth := r.BasicAuth()
if hasAuth && user == requiredUser && password == requiredPassword {
// Delegate request to the given handle
h(w, r, ps)
} else {
// Request Basic Authentication otherwise
w.Header().Set("WWW-Authenticate", "Basic realm=Restricted")
http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
}
}
}
func Index(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
fmt.Fprint(w, "Not protected!\n")
}
func Protected(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
fmt.Fprint(w, "Protected!\n")
}
func main() {
user := "gordon"
pass := "secret!"
router := httprouter.New()
router.GET("/", Index)
router.GET("/protected/", BasicAuth(Protected, user, pass))
log.Fatal(http.ListenAndServe(":8080", router))
}
Chaining with the NotFound handler
NOTE: It might be required to set Router.HandleMethodNotAllowed
to false
to avoid problems.
You can use another http.Handler
, for example another router, to handle requests which could not be matched by this router by using the Router.NotFound
handler. This allows chaining.
Static files
The NotFound
handler can for example be used to serve static files from the root path /
(like an index.html
file along with other assets):
// Serve static files from the ./public directory
router.NotFound = http.FileServer(http.Dir("public"))
But this approach sidesteps the strict core rules of this router to avoid routing problems. A cleaner approach is to use a distinct sub-path for serving files, like /static/*filepath
or /files/*filepath
.
Web Frameworks based on HttpRouter
If the HttpRouter is a bit too minimalistic for you, you might try one of the following more high-level 3rd-party web frameworks building upon the HttpRouter package:
- Ace: Blazing fast Go Web Framework
- api2go: A JSON API Implementation for Go
- Gin: Features a martini-like API with much better performance
- Goat: A minimalistic REST API server in Go
- goMiddlewareChain: An express.js-like-middleware-chain
- Hikaru: Supports standalone and Google AppEngine
- Hitch: Hitch ties httprouter, httpcontext, and middleware up in a bow
- httpway: Simple middleware extension with context for httprouter and a server with gracefully shutdown support
- intake: intake is a minimal http framework with enphasis on middleware groups
- Jett: A lightweight framework with subrouters, graceful shutdown and middleware at all levels.
- kami: A tiny web framework using x/net/context
- Medeina: Inspired by Ruby's Roda and Cuba
- nchi: provides a chi-like framework using nject for flexibility and ease-of-use
- Neko: A lightweight web application framework for Golang
- pbgo: pbgo is a mini RPC/REST framework based on Protobuf
- River: River is a simple and lightweight REST server
- siesta: Composable HTTP handlers with contexts
- xmux: xmux is a httprouter fork on top of xhandler (net/context aware)
Top Related Projects
Package gorilla/mux is a powerful HTTP router and URL matcher for building Go web servers with 🦍
Gin is a HTTP web framework written in Go (Golang). It features a Martini-like API with much better performance -- up to 40 times faster. If you need smashing performance, get yourself some Gin.
High performance, minimalist Go web framework
lightweight, idiomatic and composable router for building Go HTTP services
⚡️ Express inspired web framework written in Go
Fast HTTP package for Go. Tuned for high performance. Zero memory allocations in hot paths. Up to 10x faster than net/http
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot