Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up

A golang http router based on trie tree.

License

NotificationsYou must be signed in to change notification settings

bmf-san/goblin

Repository files navigation

English日本語

goblin

Mentioned in Awesome GoGitHub releaseCircleCIGo Report CardcodecovGitHub licenseGo ReferenceSourcegraph

A golang http router based on trie tree.

goblin

This logo was created bygopherize.me.

Table of contents

Features

  • Go1.21 >= 1.16
  • Simple data structure based on trie tree
  • Lightweight
    • Lines of codes: 2428
    • Package size: 140K
  • No dependencies other than standard packages
  • Compatible with net/http
  • More advanced than net/http'sServemux
    • Method based routing
    • Named parameter routing
    • Regular expression based routing
    • Middleware
    • Customizable error handlers
    • Default OPTIONS handler
  • 0allocs
    • Achieve 0 allocations in static routing
    • About 3allocs for named routes
      • Heap allocation occurs when creating parameter slices and storing parameters in context

Install

go get -u github.com/bmf-san/goblin

Example

A sample implementation is available.

Please refer toexample_goblin_test.go.

Usage

Method based routing

Routing can be defined based on any HTTP method.

The following HTTP methods are supported.GET/POST/PUT/PATCH/DELETE/OPTIONS

r:=goblin.NewRouter()r.Methods(http.MethodGet).Handler(`/`,http.HandlerFunc(func(w http.ResponseWriter,r*http.Request) {fmt.Fprintf(w,"/")}))r.Methods(http.MethodGet,http.MethodPost).Handler(`/methods`,http.HandlerFunc(func(w http.ResponseWriter,r*http.Request) {ifr.Method==http.MethodGet {fmt.Fprintf(w,"GET")    }ifr.Method==http.MethodPost {fmt.Fprintf(w,"POST")    }}))http.ListenAndServe(":9999",r)

Named parameter routing

You can define routing with named parameters (:paramName).

r:=goblin.NewRouter()r.Methods(http.MethodGet).Handler(`/foo/:id`,http.HandlerFunc(func(w http.ResponseWriter,r*http.Request) {id:=goblin.GetParam(r.Context(),"id")fmt.Fprintf(w,"/foo/%v",id)}))r.Methods(http.MethodGet).Handler(`/foo/:name`,http.HandlerFunc(func(w http.ResponseWriter,r*http.Request) {name:=goblin.GetParam(r.Context(),"name")fmt.Fprintf(w,"/foo/%v",name)}))http.ListenAndServe(":9999",r)

Regular expression based routing

By using regular expressions for named parameters (:paramName[pattern]), you can define routing using regular expressions.

r.Methods(http.MethodGet).Handler(`/foo/:id[^\d+$]`,http.HandlerFunc(func(w http.ResponseWriter,r*http.Request) {id:=goblin.GetParam(r.Context(),"id")fmt.Fprintf(w,"/foo/%v",id)}))

Middleware

Supports middleware to help pre-process requests and post-process responses.

Middleware can be defined for any routing.

Middleware can also be configured globally. If a middleware is configured globally, the middleware will be applied to all routing.

More than one middleware can be configured.

Middleware must be defined as a function that returns http.

// Implement middleware as a function that returns http.Handlfuncglobal(next http.Handler) http.Handler {returnhttp.HandlerFunc(func(w http.ResponseWriter,r*http.Request) {fmt.Fprintf(w,"global: before\n")next.ServeHTTP(w,r)fmt.Fprintf(w,"global: after\n")})}funcfirst(next http.Handler) http.Handler {returnhttp.HandlerFunc(func(w http.ResponseWriter,r*http.Request) {fmt.Fprintf(w,"first: before\n")next.ServeHTTP(w,r)fmt.Fprintf(w,"first: after\n")})}funcsecond(next http.Handler) http.Handler {returnhttp.HandlerFunc(func(w http.ResponseWriter,r*http.Request) {fmt.Fprintf(w,"second: before\n")next.ServeHTTP(w,r)fmt.Fprintf(w,"second: after\n")})}functhird(next http.Handler) http.Handler {returnhttp.HandlerFunc(func(w http.ResponseWriter,r*http.Request) {fmt.Fprintf(w,"third: before\n")next.ServeHTTP(w,r)fmt.Fprintf(w,"third: after\n")})}r:=goblin.NewRouter()// Set middleware globallyr.UseGlobal(global)r.Methods(http.MethodGet).Handler(`/globalmiddleware`,http.HandlerFunc(func(w http.ResponseWriter,r*http.Request) {fmt.Fprintf(w,"/globalmiddleware\n")}))// Use methods can be used to apply middlewarer.Methods(http.MethodGet).Use(first).Handler(`/middleware`,http.HandlerFunc(func(w http.ResponseWriter,r*http.Request) {fmt.Fprintf(w,"middleware\n")}))// Multiple middleware can be configuredr.Methods(http.MethodGet).Use(second,third).Handler(`/middlewares`,http.HandlerFunc(func(w http.ResponseWriter,r*http.Request) {fmt.Fprintf(w,"middlewares\n")}))http.ListenAndServe(":9999",r)

A request to/globalmiddleware gives the following results.

global: before/globalmiddlewareglobal: after

A request to/middleware gives the following results.

global: beforefirst: beforemiddlewarefirst: afterglobal: after

A request to/middlewares gives the following results.

global: beforesecond: beforethird: beforemiddlewaresthird: aftersecond: afterglobal: after

Customizable error handlers

You can define your own error handlers.

The following two types of error handlers can be defined

  • NotFoundHandler
    • Handler that is executed when no result matching the routing is obtained
  • MethodNotAllowedHandler
    • Handler that is executed when no matching method is found
funccustomMethodNotFound() http.Handler {returnhttp.HandlerFunc(func(w http.ResponseWriter,r*http.Request) {fmt.Fprintf(w,"customMethodNotFound")})}funccustomMethodAllowed() http.Handler {returnhttp.HandlerFunc(func(w http.ResponseWriter,r*http.Request) {fmt.Fprintf(w,"customMethodNotAllowed")})}r:=goblin.NewRouter()r.NotFoundHandler=customMethodNotFound()r.MethodNotAllowedHandler=customMethodAllowed()http.ListenAndServe(":9999",r)

Default OPTIONS handler

You can define a default handler that will be executed when a request is made with the OPTIONS method.

funcDefaultOPTIONSHandler(next http.Handler) http.Handler {returnhttp.HandlerFunc(func(w http.ResponseWriter,r*http.Request) {w.WriteHeader(http.StatusNoContent)})}r:=goblin.NewRouter()r.DefaultOPTIONSHandler=DefaultOPTIONSHandler()http.ListenAndServe(":9999",r)

The default OPTIONS handler is useful, for example, in handling CORS OPTIONS requests (preflight requests).

Benchmark tests

We have a command to run a goblin benchmark test.

Please refer toMakefile.

Curious about benchmark comparison results with other HTTP Routers?

Please see here!bmf-san/go-router-benchmark

Design

This section describes the internal data structure of goblin.

Whileradix tree is often employed in performance-optimized HTTP Routers, goblin usestrie tree.

Compared to radix trees, trie tree have a disadvantage in terms of performance due to inferior memory usage. However, the simplicity of the algorithm and ease of understanding are overwhelmingly in favor of the trie tree.

HTTP Router may seem like a simple application with a simple specification, but it is surprisingly complex. You can see this by looking at the test cases.(If you have an idea for a better-looking test case implementation, please let us know.)

One advantage of using a simple algorithm is that it contributes to code maintainability. (This may sound like an excuse for the difficulty of implementing a radix tree... in fact, the difficulty of implementing an HTTP Router based on a radix tree frustrated me once...)

Using the source code of_examples as an example, I will explain the internal data structure of goblin.

The routing definitions are represented in a table as follows.

MethodPathHandlerMiddleware
GET/RootHandlerN/A
GET/fooFooHandlerCORS
POST/fooFooHandlerCORS
GET/foo/barFooBarHandlerN/A
GET/foo/bar/:nameFooBarNameHandlerN/A
POST/foo/:nameFooNameHandlerN/A
GET/bazBazHandlerCORS

In gobin, such routing is represented as the following tree structure.

legend:<HTTP Method>,[Node]<GET>    ├── [/]    |    ├── [/foo]    |        |    |        └── [/bar]    |                 |    |                 └── [/:name]    |    └── [/baz]<POST>    └── [/foo]             |             └── [/:name]

The tree is constructed for each HTTP method.

Each node has handler and middleware definitions as data.

In order to simplify the explanation, data such as named routing data and global middleware data are omitted here.

Various other data is held in the internally constructed tree.

If you want to know more, use the debugger to take a peek at the internal structure.

If you have any ideas for improvements, please let us know!

Wiki

References are listed on thewiki.

Contribution

Issues and Pull Requests are always welcome.

We would be happy to receive your contributions.

Please review the following documents before making a contribution.

Sponsor

If you like it, I would be happy to have you sponsor it!

GitHub Sponsors - bmf-san

Or I would be happy to get a STAR.

It motivates me to keep up with ongoing maintenance :D

Stargazers

Stargazers repo roster for @bmf-san/goblin

Forkers

Forkers repo roster for @bmf-san/goblin

License

Based on the MIT License.

LICENSE

Author

bmf-san


[8]ページ先頭

©2009-2025 Movatter.jp