router

package module
v0.1.18 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 1, 2021 License: MIT Imports: 9 Imported by: 0

README

Router

build Coverage Status

A minimalist and fast router framework for golang. Inspired by the most popular node.js web framework, express.js. It implements ServeHTTP interface so you can use express style routing. It also wraps and extends the net/http Request and ResponseWriter into an easy to read and use function signature.

The main features are:

  • Simple router, handler, and middleware
  • The speed is up to 9 times faster than express.js
  • Chainable router, request and response.
  • Standard net/http compatible. Ready for google serverless


Get Started

Init folder and install
mkdir app
cd app
go mod init myapp
go get github.com/fastrodev/router
Create main.go file
package main

import (
	"github.com/fastrodev/router"
	"github.com/fastrodev/router/http"
)

func main() {
	app := router.New()
	app.Get("/", func(req http.Request, res http.Response) {
		res.Send("hello")
	})
	app.Listen(9000)
}

Run webapp
go run main.go
Routing

You can add a new route with all http method and http param with :param.

app.Get("/user/:id", handler)

You can append a regular expression in parentheses (())

app.Get("/user/:id([0-9]+)", handler)
Handler

The signature is similar to express.js handler.

func handler(req http.Request, res http.Response) {
	res.Send("hello")
}
Header

HTTP headers let the client and the server pass additional information with an HTTP request or response.

header := res.Header()
header.Set("sid", "123321")

A cookie is information stored on your computer by a website you visit.

Get a cookie

c, err := req.Cookie("name")

Create a cookie

c := http.NewCookie()
expire := time.Now().Add(5 * time.Minute)
c.Name("name").Value("agus").Expires(expire)

Then attach it to response

res.Cookie(c)
Context

You can add a context using the app.Ctx(ctx) function

app.Ctx(context.Background())

You can access the context from Request

ctx := req.Context()

and use it again via req.WithContext(ctx)

req = req.WithContext(ctx)
Logging

You can add a logger using the app.Log(log) function

app.Log(log.Default())
Middleware

It have access to the request, the response, and the next function in the application’s request-response cycle.

Application-level middleware
func rootMiddleware(req http.Request, res http.Response, next http.Next) {
	if req.URL.Path != "/" {
		req = req.ErrorMiddleware(std.ErrAbortHandler, std.StatusForbidden)
		next(req, res)
		return
	}
	next(req, res)
}
app.Use(rootMiddleware)
Router-level middleware
handler := func(req http.Request, res http.Response) {
	res.Send("hello")
}

middleware := func(req http.Request, res http.Response, next http.Next) {
	// put your logic here
	next(req, res)
}

app.Get("/", handler, middleware)
Example

You can find above implementations in the following source code: main.go.

Cloud Function

If you want to use serverless computing, you can deploy your codes to google cloud function. With this approach, you don't call the Listen function again. You must create a new function as the entry point for standard net/http Request and ResponseWriter.

Source code: main.go

package function

import (
	std "net/http"

	"github.com/fastrodev/router"
	"github.com/fastrodev/router/http"
)

func createRouter() router.Router {
	app := router.New()
	app.Get("/", func(req http.Request, res http.Response) {
		res.Send("Hello")
	})
	return app
}

func HelloHTTP(w std.ResponseWriter, r *std.Request) {
	createRouter().ServeHTTP(w, r)
}

How to deploy

Reference: deploying the function

gcloud functions deploy HelloHTTP --runtime go113 --trigger-http --allow-unauthenticated

Live demo: HelloHTTP

Benchmarks

Router framework vs standard net/http

You can view the details here: benchmarks

module requests/sec percentage
net/http 89475.41 100.00%
router 88044.39 98.40%
node.js 48699.82 54.42%
express.js 9685.14 10.82%

Contributing

We appreciate your help! The main purpose of this repository is to improve performance and readability, making it faster and easier to use.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Callback

type Callback func()

type Handler

type Handler func(http.Request, http.Response)

type HandlerFunc

type HandlerFunc func(http.Request, http.Response)

func (HandlerFunc) ServeHTTP

func (f HandlerFunc) ServeHTTP(w std.ResponseWriter, r *std.Request)

type Router

type Router interface {
	Get(string, Handler, ...http.Middleware) Router
	Connect(string, Handler, ...http.Middleware) Router
	Delete(string, Handler, ...http.Middleware) Router
	Head(string, Handler, ...http.Middleware) Router
	Put(string, Handler, ...http.Middleware) Router
	Patch(string, Handler, ...http.Middleware) Router
	Trace(string, Handler, ...http.Middleware) Router
	Post(string, Handler, ...http.Middleware) Router
	Use(http.Middleware) Router
	Log(*log.Logger) Router
	Ctx(context.Context) Router
	ServeHTTP(w std.ResponseWriter, r *std.Request)
	Listen(options ...interface{}) error
	Close() error
	RegisterOnShutdown(f func())
	SetKeepAlivesEnabled(v bool)
	Shutdown(ctx context.Context)
}

func New

func New() Router

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL