phi

package module
v0.0.0-...-ee6510b Latest Latest
Warning

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

Go to latest
Published: Oct 26, 2017 License: MIT Imports: 8 Imported by: 7

README

phi

GoDoc Widget Travis Widget License Widget GoReport Widget

phi is a package which ports chi to fasthttp.

Install

go get -u github.com/fate-lovely/phi

Example

package main

import (
  "log"
  "time"

  "github.com/fate-lovely/phi"
  "github.com/valyala/fasthttp"
)

func main() {
  r := phi.NewRouter()

  reqIDMW := func(next phi.HandlerFunc) phi.HandlerFunc {
    return func(ctx *fasthttp.RequestCtx) {
      next(ctx)
      ctx.WriteString("+reqid=1")
    }
  }
  r.Use(reqIDMW)

  r.Get("/", func(ctx *fasthttp.RequestCtx) {
    ctx.WriteString("index")
  })
  r.NotFound(func(ctx *fasthttp.RequestCtx) {
    ctx.WriteString("whoops, not found")
    ctx.SetStatusCode(404)
  })
  r.MethodNotAllowed(func(ctx *fasthttp.RequestCtx) {
    ctx.WriteString("whoops, bad method")
    ctx.SetStatusCode(405)
  })

  // tasks
  r.Group(func(r phi.Router) {
    mw := func(next phi.HandlerFunc) phi.HandlerFunc {
      return func(ctx *fasthttp.RequestCtx) {
        next(ctx)
        ctx.WriteString("+task")
      }
    }
    r.Use(mw)

    r.Get("/task", func(ctx *fasthttp.RequestCtx) {
      ctx.WriteString("task")
    })
    r.Post("/task", func(ctx *fasthttp.RequestCtx) {
      ctx.WriteString("new task")
    })

    caution := func(next phi.HandlerFunc) phi.HandlerFunc {
      return func(ctx *fasthttp.RequestCtx) {
        next(ctx)
        ctx.WriteString("+caution")
      }
    }
    r.With(caution).Delete("/task", func(ctx *fasthttp.RequestCtx) {
      ctx.WriteString("delete task")
    })
  })

  // cat
  r.Route("/cat", func(r phi.Router) {
    r.NotFound(func(ctx *fasthttp.RequestCtx) {
      ctx.WriteString("no such cat")
      ctx.SetStatusCode(404)
    })
    r.Use(func(next phi.HandlerFunc) phi.HandlerFunc {
      return func(ctx *fasthttp.RequestCtx) {
        next(ctx)
        ctx.WriteString("+cat")
      }
    })
    r.Get("/", func(ctx *fasthttp.RequestCtx) {
      ctx.WriteString("cat")
    })
    r.Patch("/", func(ctx *fasthttp.RequestCtx) {
      ctx.WriteString("patch cat")
    })
  })

  // user
  userRouter := phi.NewRouter()
  userRouter.NotFound(func(ctx *fasthttp.RequestCtx) {
    ctx.WriteString("no such user")
    ctx.SetStatusCode(404)
  })
  userRouter.Use(func(next phi.HandlerFunc) phi.HandlerFunc {
    return func(ctx *fasthttp.RequestCtx) {
      next(ctx)
      ctx.WriteString("+user")
    }
  })
  userRouter.Get("/", func(ctx *fasthttp.RequestCtx) {
    ctx.WriteString("user")
  })
  userRouter.Post("/", func(ctx *fasthttp.RequestCtx) {
    ctx.WriteString("new user")
  })
  r.Mount("/user", userRouter)

  server := &fasthttp.Server{
    Handler:     r.ServeFastHTTP,
    ReadTimeout: 10 * time.Second,
  }

  log.Fatal(server.ListenAndServe(":7789"))
}

output:

Path Status Code Body
GET / 200 index+reqid=1
POST / 405 whoops, bad method+reqid=1
GET /nothing 404 whoops, not found+reqid=1
GET /task 200 task+task+reqid=1
POST /task 200 new task+task+reqid=1
DELETE /task 200 delete task+caution+task+reqid=1
GET /cat 200 cat+cat+reqid=1
PATCH /cat 200 patch cat+cat+reqid=1
GET /cat/nothing 404 no such cat+cat+reqid=1
GET /user 200 user+user+reqid=1
POST /user 200 new user+user+reqid=1
GET /user/nothing 404 no such user+user+reqid=1

License

Licensed under MIT License

Documentation

Overview

Package phi is a small, idiomatic and composable router for building HTTP services.

phi requires Go 1.7 or newer.

Example:

package main

import (
  "log"
  "time"

  "github.com/fate-lovely/phi"
  "github.com/valyala/fasthttp"
)

func main() {
  r := phi.NewRouter()

  reqIDMW := func(next phi.HandlerFunc) phi.HandlerFunc {
    return func(ctx *fasthttp.RequestCtx) {
      next(ctx)
      ctx.WriteString("+reqid=1")
    }
  }
  r.Use(reqIDMW)

  r.Get("/", func(ctx *fasthttp.RequestCtx) {
    ctx.WriteString("index")
  })
  r.NotFound(func(ctx *fasthttp.RequestCtx) {
    ctx.WriteString("whoops, not found")
    ctx.SetStatusCode(404)
  })
  r.MethodNotAllowed(func(ctx *fasthttp.RequestCtx) {
    ctx.WriteString("whoops, bad method")
    ctx.SetStatusCode(405)
  })

  // tasks
  r.Group(func(r phi.Router) {
    mw := func(next phi.HandlerFunc) phi.HandlerFunc {
      return func(ctx *fasthttp.RequestCtx) {
        next(ctx)
        ctx.WriteString("+task")
      }
    }
    r.Use(mw)

    r.Get("/task", func(ctx *fasthttp.RequestCtx) {
      ctx.WriteString("task")
    })
    r.Post("/task", func(ctx *fasthttp.RequestCtx) {
      ctx.WriteString("new task")
    })

    caution := func(next phi.HandlerFunc) phi.HandlerFunc {
      return func(ctx *fasthttp.RequestCtx) {
        next(ctx)
        ctx.WriteString("+caution")
      }
    }
    r.With(caution).Delete("/task", func(ctx *fasthttp.RequestCtx) {
      ctx.WriteString("delete task")
    })
  })

  // cat
  r.Route("/cat", func(r phi.Router) {
    r.NotFound(func(ctx *fasthttp.RequestCtx) {
      ctx.WriteString("no such cat")
      ctx.SetStatusCode(404)
    })
    r.Use(func(next phi.HandlerFunc) phi.HandlerFunc {
      return func(ctx *fasthttp.RequestCtx) {
        next(ctx)
        ctx.WriteString("+cat")
      }
    })
    r.Get("/", func(ctx *fasthttp.RequestCtx) {
      ctx.WriteString("cat")
    })
    r.Patch("/", func(ctx *fasthttp.RequestCtx) {
      ctx.WriteString("patch cat")
    })
  })

  // user
  userRouter := phi.NewRouter()
  userRouter.NotFound(func(ctx *fasthttp.RequestCtx) {
    ctx.WriteString("no such user")
    ctx.SetStatusCode(404)
  })
  userRouter.Use(func(next phi.HandlerFunc) phi.HandlerFunc {
    return func(ctx *fasthttp.RequestCtx) {
      next(ctx)
      ctx.WriteString("+user")
    }
  })
  userRouter.Get("/", func(ctx *fasthttp.RequestCtx) {
    ctx.WriteString("user")
  })
  userRouter.Post("/", func(ctx *fasthttp.RequestCtx) {
    ctx.WriteString("new user")
  })
  r.Mount("/user", userRouter)

  server := &fasthttp.Server{
    Handler:     r.ServeFastHTTP,
    ReadTimeout: 10 * time.Second,
  }

  log.Fatal(server.ListenAndServe(":7789"))
}

See github.com/fate-lovely/phi/examples/ for more in-depth examples.

Index

Constants

This section is empty.

Variables

View Source
var (
	// RouteCtxKey is the context.Context key to store the request context.
	RouteCtxKey = (&contextKey{"RouteContext"}).String()
)

Functions

func RegisterMethod

func RegisterMethod(method string)

RegisterMethod registers new methods which can be used in `Router.Method` call

func URLParam

func URLParam(ctx *fasthttp.RequestCtx, key string) string

URLParam returns the url parameter from *fasthttp.RequestCtx

func Walk

func Walk(r Routes, walkFn WalkFunc) error

Walk walks any router tree that implements Routes interface.

Types

type ChainHandler

type ChainHandler struct {
	Middlewares Middlewares
	Endpoint    Handler
	// contains filtered or unexported fields
}

ChainHandler is a phi.Handler with support for handler composition and execution.

func (*ChainHandler) ServeFastHTTP

func (c *ChainHandler) ServeFastHTTP(ctx *fasthttp.RequestCtx)

type Context

type Context struct {
	Routes Routes

	// Routing path/method override used during the route search.
	// See Mux#routeHTTP method.
	RoutePath   string
	RouteMethod string

	// Routing pattern stack throughout the lifecycle of the request,
	// across all connected routers. It is a record of all matching
	// patterns across a stack of sub-routers.
	RoutePatterns []string

	// URLParams are the stack of routeParams captured during the
	// routing lifecycle across a stack of sub-routers.
	URLParams RouteParams
	// contains filtered or unexported fields
}

Context is the default routing context set on the root node of a request context to track route patterns, URL parameters and an optional routing path.

func NewRouteContext

func NewRouteContext() *Context

NewRouteContext returns a new routing Context object.

func RouteContext

func RouteContext(ctx *fasthttp.RequestCtx) *Context

RouteContext returns phi's routing Context object from *fasthttp.RequestCtx

func (*Context) Reset

func (x *Context) Reset()

Reset a routing context to its initial state.

func (*Context) RoutePattern

func (x *Context) RoutePattern() string

RoutePattern builds the routing pattern string for the particular request, at the particular point during routing. This means, the value will change throughout the execution of a request in a router. That is why its advised to only use this value after calling the next handler.

For example,

func Instrument(next phi.HandlerFunc) phi.HandlerFunc {
  return func(ctx *fasthttp.RequestCtx) {
    next(ctx)
    routePattern := phi.RouteContext(ctx).RoutePattern()
    measure(w, r, routePattern)
	 })
}

func (*Context) URLParam

func (x *Context) URLParam(key string) string

URLParam returns the corresponding URL parameter value from the request routing context.

type Handler

type Handler interface {
	ServeFastHTTP(ctx *fasthttp.RequestCtx)
}

Handler represents a fasthttp request handler, it has one method: ServeFastHTTP, which is equal to fasthttp.RequestHandler

type HandlerFunc

type HandlerFunc func(ctx *fasthttp.RequestCtx)

HandlerFunc type is an adapter to allow the use of ordinary functions as handlers.

func (HandlerFunc) ServeFastHTTP

func (fn HandlerFunc) ServeFastHTTP(ctx *fasthttp.RequestCtx)

ServeFastHTTP calss fn(ctx)

type Middleware

type Middleware func(HandlerFunc) HandlerFunc

Middleware represents phi middlewares, which accept a HandlerFunc and return a HandlerFunc

type Middlewares

type Middlewares []Middleware

Middlewares type is a slice of standard middleware handlers with methods to compose middleware chains and phi.Handler's. type Middlewares []func(Handler) Handler

func Chain

func Chain(middlewares ...Middleware) Middlewares

Chain returns a Middlewares type from a slice of middleware handlers.

func (Middlewares) Handler

func (mws Middlewares) Handler(h Handler) Handler

Handler builds and returns a phi.Handler from the chain of middlewares, with `h phi.HandlerFunc` as the final handler.

func (Middlewares) HandlerFunc

func (mws Middlewares) HandlerFunc(h HandlerFunc) Handler

HandlerFunc builds and returns a phi.Handler from the chain of middlewares, with `h phi.HandlerFunc` as the final handler.

type Mux

type Mux struct {
	// contains filtered or unexported fields
}

Mux is a simple HTTP route multiplexer that parses a request path, records any URL params, and executes an end handler. It implements the phi.Handler interface and is friendly with the standard library.

Mux is designed to be fast, minimal and offer a powerful API for building modular and composable HTTP services with a large set of handlers. It's particularly useful for writing large REST API services that break a handler into many smaller parts composed of middlewares and end handlers.

func NewMux

func NewMux() *Mux

NewMux returns a newly initialized Mux object that implements the Router interface.

func NewRouter

func NewRouter() *Mux

NewRouter returns a new Mux object that implements the Router interface.

func (*Mux) Connect

func (mx *Mux) Connect(pattern string, handlerFn HandlerFunc)

Connect adds the route `pattern` that matches a CONNECT http method to execute the `handlerFn` phi.HandlerFunc.

func (*Mux) Delete

func (mx *Mux) Delete(pattern string, handlerFn HandlerFunc)

Delete adds the route `pattern` that matches a DELETE http method to execute the `handlerFn` phi.HandlerFunc.

func (*Mux) Get

func (mx *Mux) Get(pattern string, handlerFn HandlerFunc)

Get adds the route `pattern` that matches a GET http method to execute the `handlerFn` phi.HandlerFunc.

func (*Mux) Group

func (mx *Mux) Group(fn func(r Router))

Group creates a new inline-Mux with a fresh middleware stack. It's useful for a group of handlers along the same routing path that use an additional set of middlewares. See _examples/.

func (*Mux) Handle

func (mx *Mux) Handle(pattern string, handler HandlerFunc)

Handle adds the route `pattern` that matches any http method to execute the `handler` phi.Handler.

func (*Mux) Head

func (mx *Mux) Head(pattern string, handlerFn HandlerFunc)

Head adds the route `pattern` that matches a HEAD http method to execute the `handlerFn` phi.HandlerFunc.

func (*Mux) Match

func (mx *Mux) Match(rctx *Context, method, path string) bool

Match searches the routing tree for a handler that matches the method/path. It's similar to routing a http request, but without executing the handler thereafter.

Note: the *Context state is updated during execution, so manage the state carefully or make a NewRouteContext().

func (*Mux) Method

func (mx *Mux) Method(method, pattern string, handler HandlerFunc)

Method adds the route `pattern` that matches `method` http method to execute the `handler` phi.Handler.

func (*Mux) MethodNotAllowed

func (mx *Mux) MethodNotAllowed(handlerFn HandlerFunc)

MethodNotAllowed sets a custom phi.HandlerFunc for routing paths where the method is unresolved. The default handler returns a 405 with an empty body.

func (*Mux) MethodNotAllowedHandler

func (mx *Mux) MethodNotAllowedHandler() HandlerFunc

MethodNotAllowedHandler returns the default Mux 405 responder whenever a method cannot be resolved for a route.

func (*Mux) Middlewares

func (mx *Mux) Middlewares() Middlewares

Middlewares returns a slice of middleware handler functions.

func (*Mux) Mount

func (mx *Mux) Mount(pattern string, handler Handler)

Mount attaches another phi.Handler or phi Router as a subrouter along a routing path. It's very useful to split up a large API as many independent routers and compose them as a single service using Mount. See _examples/.

Note that Mount() simply sets a wildcard along the `pattern` that will continue routing at the `handler`, which in most cases is another phi.Router. As a result, if you define two Mount() routes on the exact same pattern the mount will panic.

func (*Mux) NotFound

func (mx *Mux) NotFound(handlerFn HandlerFunc)

NotFound sets a custom phi.HandlerFunc for routing paths that could not be found. The default 404 handler is `ctx.NotFound()`.

func (*Mux) NotFoundHandler

func (mx *Mux) NotFoundHandler() HandlerFunc

NotFoundHandler returns the default Mux 404 responder whenever a route cannot be found.

func (*Mux) Options

func (mx *Mux) Options(pattern string, handlerFn HandlerFunc)

Options adds the route `pattern` that matches a OPTIONS http method to execute the `handlerFn` phi.HandlerFunc.

func (*Mux) Patch

func (mx *Mux) Patch(pattern string, handlerFn HandlerFunc)

Patch adds the route `pattern` that matches a PATCH http method to execute the `handlerFn` phi.HandlerFunc.

func (*Mux) Post

func (mx *Mux) Post(pattern string, handlerFn HandlerFunc)

Post adds the route `pattern` that matches a POST http method to execute the `handlerFn` phi.HandlerFunc.

func (*Mux) Put

func (mx *Mux) Put(pattern string, handlerFn HandlerFunc)

Put adds the route `pattern` that matches a PUT http method to execute the `handlerFn` phi.HandlerFunc.

func (*Mux) Route

func (mx *Mux) Route(pattern string, fn func(r Router))

Route creates a new Mux with a fresh middleware stack and mounts it along the `pattern` as a subrouter. Effectively, this is a short-hand call to Mount. See _examples/.

func (*Mux) Routes

func (mx *Mux) Routes() []Route

Routes returns a slice of routing information from the tree, useful for traversing available routes of a router.

func (*Mux) ServeFastHTTP

func (mx *Mux) ServeFastHTTP(ctx *fasthttp.RequestCtx)

ServeFastHTTP is the single method of the phi.Handler interface that makes Mux interoperable with the standard library. It uses a sync.Pool to get and reuse routing contexts for each request.

func (*Mux) Trace

func (mx *Mux) Trace(pattern string, handlerFn HandlerFunc)

Trace adds the route `pattern` that matches a TRACE http method to execute the `handlerFn` phi.HandlerFunc.

func (*Mux) Use

func (mx *Mux) Use(middlewares ...Middleware)

Use appends a middleware handler to the Mux middleware stack.

The middleware stack for any Mux will execute before searching for a matching route to a specific handler, which provides opportunity to respond early, change the course of the request execution, or set request-scoped values for the next phi.Handler.

func (*Mux) With

func (mx *Mux) With(middlewares ...Middleware) Router

With adds inline middlewares for an endpoint handler.

type Route

type Route struct {
	Pattern   string
	Handlers  map[string]Handler
	SubRoutes Routes
}

Route describes the details of a routing handler.

type RouteParams

type RouteParams struct {
	Keys, Values []string
}

RouteParams is a structure to track URL routing parameters efficiently.

func (*RouteParams) Add

func (s *RouteParams) Add(key, value string)

Add will append a URL parameter to the end of the route param

type Router

type Router interface {
	Handler
	Routes

	// Use appends one of more middlewares onto the Router stack.
	Use(middlewares ...Middleware)

	// With adds inline middlewares for an endpoint handler.
	With(middlewares ...Middleware) Router

	// Group adds a new inline-Router along the current routing
	// path, with a fresh middleware stack for the inline-Router.
	Group(fn func(r Router))

	// Route mounts a sub-Router along a `pattern“ string.
	Route(pattern string, fn func(r Router))

	// Mount attaches another phi.Handler along ./pattern/*
	Mount(pattern string, h Handler)

	// Handle and HandleFunc adds routes for `pattern` that matches
	// all HTTP methods.
	Handle(pattern string, h HandlerFunc)

	// Method and MethodFunc adds routes for `pattern` that matches
	// the `method` HTTP method.
	Method(method, pattern string, h HandlerFunc)

	// HTTP-method routing along `pattern`
	Connect(pattern string, h HandlerFunc)
	Delete(pattern string, h HandlerFunc)
	Get(pattern string, h HandlerFunc)
	Head(pattern string, h HandlerFunc)
	Options(pattern string, h HandlerFunc)
	Patch(pattern string, h HandlerFunc)
	Post(pattern string, h HandlerFunc)
	Put(pattern string, h HandlerFunc)
	Trace(pattern string, h HandlerFunc)

	// NotFound defines a handler to respond whenever a route could
	// not be found.
	NotFound(h HandlerFunc)

	// MethodNotAllowed defines a handler to respond whenever a method is
	// not allowed.
	MethodNotAllowed(h HandlerFunc)
}

Router consisting of the core routing methods used by phi's Mux,

type Routes

type Routes interface {
	// Routes returns the routing tree in an easily traversable structure.
	Routes() []Route

	// Middlewares returns the list of middlewares in use by the router.
	Middlewares() Middlewares

	// Match searches the routing tree for a handler that matches
	// the method/path - similar to routing a http request, but without
	// executing the handler thereafter.
	Match(rctx *Context, method, path string) bool
}

Routes interface adds two methods for router traversal, which is also used by the `docgen` subpackage to generation documentation for Routers.

type WalkFunc

type WalkFunc func(method string, route string, handler Handler, middlewares ...Middleware) error

WalkFunc is the type of the function called for each method and route visited by Walk.

Jump to

Keyboard shortcuts

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