Skip to content

jspc/routes

Repository files navigation

GoDoc Go Report Card CircleCI Codecov Code Climate maintainability

routes

import "github.com/jspc/routes"

Package routes is a small, no-frills routing library for fasthttp. It's designed to sit within a fasthttp aware service to determine which route, from a map, to direct a ctx at.

It is designed:

  1. To contain no third party module (beyond fasthttp)

  2. To be as unobtrusive as possible

    package main

    import (
       "fmt"

       "github.com/jspc/routes"
       "github.com/valyala/fasthttp"
    )

    type API struct {
       Message string
    }

    func (a API) Hello(ctx *fasthttp.RequestCtx) {
       name := ctx.UserValue("name").(string)

       fmt.Fprintf(ctx, "%s %s", a.Message, name)
    }

    func (a API) FourOhFour(ctx *fasthttp.RequestCtx) {
       ctx.SetStatusCode(fasthttp.StatusNotFound)

       fmt.Fprintf(ctx, "%s not found", string(ctx.Path()))
    }

    func (a API) Handle(ctx *fasthttp.RequestCtx) {
       r := routes.New()
       r.Catcher = a.FourOhFour

       r.Add("/hello/:name", a.Hello)

       r.Route(ctx)
    }

    func main() {
       panic(fasthttp.ListenAndServe(":8080", API{"Hello"}.Handle))
       }

The above will return Hello james for GET /hello/james, and a 404 for anything else.

doc.go routes.go

type Routes struct {
    Routes  map[string]fasthttp.RequestHandler
    Catcher fasthttp.RequestHandler
}

Routes represents the fasthttp aware routes and configuration that determine which route to choose

func New() *Routes

New is a friendly, convenience function for returning an instance of routes.Routes that can be used in client code

func (*Routes) Add

func (r *Routes) Add(pattern string, f fasthttp.RequestHandler)

Add takes a pattern, a function, and adds them to its self so requests can be routed correctly.

A pattern can be a full url, or can use parameters. Params in URLs look like:

/users/:user/address

This would match on:

/users/12345/address

(For instance)

Add() does no checking for existing routes; it is the responsibility of the developer to ensure there are no duplicates. The last function assigned to a patter will be used.

func (Routes) Route

func (r Routes) Route(ctx *fasthttp.RequestCtx)

Route will send a fasthttp request to the correct function based on the path in the request. Parameters, as defined in a route, are accessed by ctx.userValue(param)


Generated by godoc2md