All Projects → beego → Mux

beego / Mux

Licence: apache-2.0
A high performance and powerful trie based url path router for Go.

Programming Languages

go
31211 projects - #10 most used programming language
golang
3204 projects

Projects that are alternatives of or similar to Mux

Mux
A powerful HTTP router and URL matcher for building Go web servers with 🦍
Stars: ✭ 15,667 (+3117.04%)
Mutual labels:  mux, router
Httprouter
A high performance HTTP request router that scales well
Stars: ✭ 13,500 (+2672.07%)
Mutual labels:  mux, router
Bone
Lightning Fast HTTP Multiplexer
Stars: ✭ 1,270 (+160.78%)
Mutual labels:  mux, router
rux
⚡ Rux is an simple and fast web framework. support route group, param route binding, middleware, compatible http.Handler interface. 简单且快速的 Go api/web 框架,支持路由分组,路由参数绑定,中间件,兼容 http.Handler 接口
Stars: ✭ 81 (-83.37%)
Mutual labels:  router, mux
Auto route library
Flutter route generator
Stars: ✭ 434 (-10.88%)
Mutual labels:  router
Blacklist
Blacklist and Adware Blocking for the Ubiquiti EdgeMax Router
Stars: ✭ 393 (-19.3%)
Mutual labels:  router
Sower
Sower is a cross-platform intelligent transparent proxy solution.
Stars: ✭ 391 (-19.71%)
Mutual labels:  router
React
🔼 UI-Router for React
Stars: ✭ 386 (-20.74%)
Mutual labels:  router
Uni Simple Router
a simple, lightweight routing plugin that supports interception and lifecycle triggering
Stars: ✭ 481 (-1.23%)
Mutual labels:  router
Gearbox
Gearbox ⚙️ is a web framework written in Go with a focus on high performance
Stars: ✭ 455 (-6.57%)
Mutual labels:  router
Joi Router
Configurable, input and output validated routing for koa
Stars: ✭ 418 (-14.17%)
Mutual labels:  router
Diet
A tiny, fast and modular node.js web framework. Good for making fast & scalable apps and apis.
Stars: ✭ 394 (-19.1%)
Mutual labels:  router
Router
🛣 Simple Navigation for iOS
Stars: ✭ 438 (-10.06%)
Mutual labels:  router
Dcurlrouter
通过自定义URL实现控制器之间的跳转
Stars: ✭ 393 (-19.3%)
Mutual labels:  router
Next Connect
The TypeScript-ready, minimal router and middleware layer for Next.js, Micro, Vercel, or Node.js http/http2
Stars: ✭ 454 (-6.78%)
Mutual labels:  router
Regexparam
A tiny (308B) utility that converts route patterns into RegExp. Limited alternative to `path-to-regexp` 🙇‍♂️
Stars: ✭ 390 (-19.92%)
Mutual labels:  router
Portmapper
A tool for managing port forwardings via UPnP
Stars: ✭ 416 (-14.58%)
Mutual labels:  router
Iris
The fastest HTTP/2 Go Web Framework. AWS Lambda, gRPC, MVC, Unique Router, Websockets, Sessions, Test suite, Dependency Injection and more. A true successor of expressjs and laravel | 谢谢 https://github.com/kataras/iris/issues/1329 |
Stars: ✭ 21,587 (+4332.65%)
Mutual labels:  router
Beego blog
beego+layui go入门开发 简洁美观的个人博客系统
Stars: ✭ 410 (-15.81%)
Mutual labels:  beego
Routersdk
A mini and excellent Router Framwork一款小而美的路由框架。网页动态添加自定义参数启动应用。 https://github.com/Jomes/routerSDK
Stars: ✭ 402 (-17.45%)
Mutual labels:  router

mux

Build Status Coverage Status GoDoc

A high performance and powerful trie based url path router for Go.

This router supports fixed and regex rules in routing pattern, and matches request method. It's optimized by trie structure for faster matching and large scale rules.

requirement: Go 1.7+

Feature

todo

Usage

This is a simple example for mux. Read godoc to get full api documentation.

There is a basic example:

package main

import (
    	"fmt"
	"log"
	"net/http"

	"github.com/beego/mux"
)

func main() {
	mx := mux.New()
	mx.Get("/", func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte("hello, beego mux"))
	})
	mx.Get("/abc/:id", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintf(w, "hello, abc page %s", mux.Param(r,":id"))
	})

	log.Fatal(http.ListenAndServe("127.0.0.1:9999", mx))
}

Register route mapping as http.HandleFunc via http method name:

mx.Get("/get", getHandleFunc)
mx.Post("/post", postHandleFunc)
mx.Put("/put", putHandleFunc)
mx.Delete("/delete", deleteHandleFunc)
mx.Head("/head", headHandleFunc)
mx.Options("/options", optionsHandleFunc)
mx.Patch("/patch", patchHandleFunc)

Or use raw api to add route with http method name:

mx.Handle("GET", "/abc", abcHandleFunc)

Register http.Handle.

mx2 := mux.New()
mx.Get("/ttt", getHandleFunc)
mx.Handler("GET","/abc", mx2) // /abc/ttt -> getHandleFunc

default handler

Register default handle to resolve missing matches. If can not find matched pattern, mux runs default handler if set.

mx.Get("/abc",abcHandleFunc)
mx.DefaultHandler(defaultHandleFunc)
// abc -> abcHandleFunc
// ^abc -> defaultHandleFunc

Routing

The routing pattern can set as fixed pattern as most simple way. When using fixed pattern, it supports to parse json, xml and html extension to match pattern.

Pattern: /abc/xyz

/abc/xyz        matched
/abc/xyz.html   matched 
/abc/xyz.json   matched 
/abc/xyz.xml    matched 
/abc/xzz        no matched

But in common cases, you need parameters to match differenct segments in path.

Named parameters

As you see, :id is a named parameter. The matched parameters can read one via mux.Param method from *http.Request by parameter's name.

// r is *http.Request
fmt.Println(mux.Param(r,":id"))

Or read all parameters by mux.Params.

// r is *http.Request
fmt.Println(mux.Params(r))
// e.g. map[🆔1 :name:beego]

A named parameter only can match single segment of path with extension.

Pattern: /abc/:id

/abc/           no match
/abc/123        matched     (:id is 123)
/abc/xyz        matched     (:id is xyz)
/abc/123/xyz    no matched
/abc/123.html   matched     (:id is 123.html)

Wildcard parameters

If you need to match several segments in path, use * and *.* named wildcard parameters.

* matches all segments between previous and next segment node in pattern. The matched segement parts are stored in params with key :splat.

Pattern: /abc/*/xyz

/abc/xyz                no match
/abc/123/xyz            matched     (:splat is 123)
/abc/12/34/xyz          matched     (:splat is 12/34)  

*.* has familar behaviour with *, but matched results are two parts, :path as path segment and :ext as extension suffix.

Pattern : /abc/*.*

/abc/xyz.json           matched     (:path is xyz, :ext is json)
/abc/123/xyz.html       matched     (:path is 123/xyz, :ext is html)

Regexp parameters

mux supports a regular expression as a paramter , named regexp paramaters. You can set a regexp into pattern with a name placeholder.

Pattern : /abc/:id([0-9]+)

/abc/123                matched     (:id is 123)
/abc/xyz                no matched

You can set value type for one named paramater to simplify some common regexp rules. Now support :int ([0-9]+) and :string ([\w]+).

Pattern: /abc/🆔int

/abc/123        matched (:id is 123)
/abc/xyz        no match

Regexp paramters can match several parts in one segment in path.

Pattern: /abc/article_🆔int

/abc/123            no matched
/abc/article_123    matched     (:id is 123)
/abc/article_xyz    no matched

Optional parameters

If the parameter can be not found in pattern when matching url, use ? to declare this situation. ? support named and regexp parameters.

Pattern: /abc/xyz/?:id

/abc/xyz/               matched     (:id is empty)
/abc/xyz/123            matched     (:id is 123)
Pattern: /abc/xyz/?🆔int

/abc/xyz/               matched     (:id is empty)
/abc/xyz/123            matched     (:id is 123)
/abc/xyz/aaa            no matched

Complex patterns

The fixed segements, named parameters and regexp patterns can be used in one rule together.

Pattern: /article/:id/comment_:page:int

/article/12/comment_2       matched     (:id is 12, :page is 2)
/article/abc/comment_3      matched     (:id is abc, :page is 3)
/article/abc/comment_xyz    no match
Pattern: /data/:year/*/list

/data/2012/11/12/list       matched     (:year is 2012, :splat is 11/12)
/data/2014/12/list          matched     (:year is 2014, :splat is 12)
Pattern: /pic/:width:int/:height:int/*.*

/pic/20/20/aaaaaa.jpg      matched     (:width is 20, :height is 20, :path is aaaaaa, :ext is jpg)

pattern matching order

Static pattern > parameters' pattern > regexp pattern.

URL : /abc/99

pattern: /abc/99            matched
pattern: /abc/:id           no match
pattern: /abc/🆔int       no match

URL : /abc/123

pattern: /abc/99            no match
pattern: /abc/:id           matched    (:id is 123)
pattern: /abc/🆔int       no match

If register confusing patterns, it matches first one in adding order. For example, in regexp patterns:

mx := mux.New()

mx.Get("/abc/?🆔int", func(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "abc, int params %v", mux.Params(r))
})
mx.Get("/abc/?:name:string", func(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "abc, string params %v", mux.Params(r))
})

mx.Get("/xyz/?:name:string", func(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "xyz, string params %v", mux.Params(r))
})
mx.Get("/xyz/?🆔int", func(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "xyz, int params %v", mux.Params(r))
})

When using this mx to match urls, it shows result:

URL				Pattern
/abc		->		/abc/?🆔int			(first one)
/abc/123	->		/abc/?🆔int
/abc/zzz	->		/abc/?:name:string

/xyz		->		/xyz/?:name:string		(first one)
/xyz/123	->		/xyz/?:name:string		(123 is treated as string "123")
/xyz/zzz	->		/xyz/?:name:string
Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].