router

package
v0.0.0-...-772259c Latest Latest
Warning

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

Go to latest
Published: Nov 15, 2021 License: Apache-2.0 Imports: 7 Imported by: 0

README

GhastRouter

Setting up route bindings in Ghast

GhastRouter has support for all the common HTTP verbs and allows you to setup your routes based off of HTTP Verb and path.

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

	ghastRouter "github.com/bradcypert/ghast/pkg/router"
)

func main() {
	router := ghastRouter.Router{}

	router.Get("/", func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(http.StatusOK)
		fmt.Fprint(w, "Hello from Ghast!")
	})

	s := router.DefaultServer()
	log.Fatal(s.ListenAndServe())
}
Path Variables

GhastRouter also allows you to specify a flexible route pattern that can be used to retrieve values from the route.

router.Get("/:name", func(w http.ResponseWriter, r *http.Request) {
    w.WriteHeader(http.StatusOK)
    fmt.Fprint(w, "Hello "+router.PathParam(r, "name").(string))
})
Using Middleware with GhastRouter

GhastRouter supports two different styles of middleware.

Global Middleware is triggered on any route match before we delegate to your handler func. Route specific middleware is triggered on the route it is specified on before we delegate to your handler func.

Global middleware is triggered before route specific middleware.

router := ghastRouter.Router{}

middleware := []ghastRouter.MiddlewareFunc{
    func(rw *http.ResponseWriter, req *http.Request) {
        fmt.Println("Incoming Request: " + req.URL.String())
    },
}

router.AddMiddleware(middleware)
Using Route Specific Middleware

GhastRouter also supports middleware for a single route. Middleware declaration is variadic so more middlewares can be added simply by adding them to the router.Get function call.

middleware := func(rw *http.ResponseWriter, req *http.Request) {
	fmt.Println("Incoming Request: " + req.URL.String())
},

router.Get("/:name", func(w http.ResponseWriter, r *http.Request) {
    w.WriteHeader(http.StatusOK)
    fmt.Fprint(w, "Hello "+r.Context().Value("name").(string))
}, middleware)
Resources

The GhastRouter module also exposes an interface for Resources (named Resource). This interface defines the expectations for a struct (usually a controller) that successfully implements a common series of request handlers. In the case of Resource, the struct needs to implement Index (intended to list all items requested), Get (intended to list a single item requested), Update (update a single item), Delete (delete a single item), and Create (create a single item).

When a struct successfully implements Resource, you can leverage the router's .Resource method to generate the routes for that struct.

type UserController struct {
	/// Implement resource here
}

router.Resource("/v1/", UserController{})
Merging Multiple Routers

Ghast can also merge multiple routers together. This is a pattern that you may use if you need to apply a certain prefix or middleware to a group of routes, but not all of them.

router := Router{}
subrouter := Router{}

var name string

subrouter.Get("/:name", func(w http.ResponseWriter, r *http.Request) {
	name = router.PathParam(r, "name").(string)
})

router.Base("/v1").Merge(&subrouter)

// this gives you a GET route at /v1/:name that responds with the handler func declared above.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Binding

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

Binding maps a url pattern to an HTTP handler

type MiddlewareFunc

type MiddlewareFunc = func(next http.Handler) http.Handler

MiddlewareFunc type alias for a function that takes in a http.Handler and returns an HTTP Handler

	func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
			curContext := req.Context()
			req = req.Clone(context.WithValue(curContext, KEY, "BAR"))

			next.ServeHTTP(w, req)
		})
 }

type Resource

type Resource interface {
	GetName() string
	Index(req *http.Request) (Response, error)
	Get(req *http.Request) (Response, error)
	Create(req *http.Request) (Response, error)
	Update(req *http.Request) (Response, error)
	Delete(req *http.Request) (Response, error)
}

Resource an interface that includes functionality intended to be used with fetching a list of items, getting a single item, creating a single item, updating a single item, and deleting a single item

type Response

type Response struct {
	Status  int
	Body    interface{}
	Headers http.Header
	Length  int
}

Response a struct to define what a controller-based response looks like

type RouteFunc

type RouteFunc func(req *http.Request) (Response, error)

RouteFunc a type alias for controller actions Controllers only have the request exposed to them as the response writer is handled by the Ghast framework.

func (RouteFunc) ServeHTTP

func (rf RouteFunc) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP calls f(r).

type Router

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

Router struct models our routes to match off of and their behavior

func (*Router) AddMiddleware

func (r *Router) AddMiddleware(fn []MiddlewareFunc) *Router

AddMiddleware registers a new global middleware within the router global middlewares will be called on any route that matches a route binding

func (*Router) Base

func (r *Router) Base(prefix string) *Router

Base set the basepath for this router segment

func (*Router) Connect

func (r *Router) Connect(route string, f http.Handler, middleware ...MiddlewareFunc) *Router

Connect registers a new CONNECT route with the router

func (Router) DefaultServer

func (r Router) DefaultServer() *http.Server

DefaultServer is an optional method to help get a preconfigured server with the router bound as the handler and some sensible defaults

func (*Router) Delete

func (r *Router) Delete(route string, f http.Handler, middleware ...MiddlewareFunc) *Router

Delete registers a new DELETE route with the router

func (*Router) Get

func (r *Router) Get(route string, f http.Handler, middleware ...MiddlewareFunc) *Router

Get registers a new GET route with the router

func (*Router) Head

func (r *Router) Head(route string, f http.Handler, middleware ...MiddlewareFunc) *Router

Head registers a new HEAD route with the router

func (*Router) Merge

func (r *Router) Merge(routers ...*Router) *Router

Merge merges one or more routers into the calling Router

func (*Router) Options

func (r *Router) Options(route string, f http.Handler, middleware ...MiddlewareFunc) *Router

Options registers a new OPTIONS route with the router

func (*Router) Patch

func (r *Router) Patch(route string, f http.Handler, middleware ...MiddlewareFunc) *Router

Patch registers a new PATCH route with the router

func (*Router) PathParam

func (r *Router) PathParam(req *http.Request, key string) interface{}

PathParam Get a Path Parameter from a given request and key

func (*Router) Post

func (r *Router) Post(route string, f http.Handler, middleware ...MiddlewareFunc) *Router

Post registers a new POST route with the router

func (*Router) Put

func (r *Router) Put(route string, f http.Handler, middleware ...MiddlewareFunc) *Router

Put registeres a new PUT route with the router

func (*Router) QueryParam

func (r *Router) QueryParam(req *http.Request, key string) interface{}

PathParam Get a Path Parameter from a given request and key

func (*Router) Resource

func (r *Router) Resource(prefix string, resource Resource)

Resource takes in a Controller Resource and generates Index, Get, Create, Delete and Update routes for that resource. Prefix is a string for any scoping or namespacing for the resource For example, you can pass "/v1/" as a Prefix for a Resource where getName returns "user" which would create the following routes: GET /v1/user GET /v1/user/:id POST /v1/user DELETE /v1/user/:id UPDATE /v1/user/:id

func (Router) ServeHTTP

func (r Router) ServeHTTP(rw http.ResponseWriter, req *http.Request)

ServeHTTP allows the router to adhere to the handler func requirements Delegates requests to provided routes

func (*Router) SetDIContainer

func (r *Router) SetDIContainer(c *ghastContainer.Container)

SetDIContainer sets up the DI container that this router will use. The provided DI container will be available in all controllers via context (or controller helpers)

func (*Router) Trace

func (r *Router) Trace(route string, f http.Handler, middleware ...MiddlewareFunc) *Router

Trace registers a new TRACE route with the router

Jump to

Keyboard shortcuts

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