router

package module
v3.4.2 Latest Latest
Warning

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

Go to latest
Published: May 11, 2023 License: GPL-2.0 Imports: 12 Imported by: 5

README

Golang HTTP Router

For people who need simple routing, with a lot of fine grained control
yet still simple enough to not make everything a hassle.

Installation

go get github.com/Nigel2392/router/v3@latest

Usage

Registering routes
func indexFunc(req *request.Request) {
    // Sessions are only available when using a middleware which defines
    // the request.Session variable.
	req.Session.Set("Hello", "World")

    // Write to the response
    req.WriteString("Index!")
}

func variableFunc(req *request.Request) {
    // Get from the session
    // Sessions are only available when using a middleware which defines
    // the request.Session variable.
    fmt.Println(rq.Session.Get("Hello"))
    // Get from the URL parameters, write to the response.
	for k, v := range rq.URLParams {
		rq.WriteString(fmt.Sprintf("%s: %s ", k, v))
	}
}

func defaultJSONFunc(req *request.Request) {
    // Easily render JSON responses!
    req.JSON.Encode(map[string]interface{}{
        "Hello": "World",
    })
}

// Configuration options for the router
var Config = &router.Config{
	// Server options.
	Host: "localhost",
	Port: 8080,
	// Recommended to be true!
	SkipTrailingSlash: true,
	// The server to use,
	// if nil, a new http.Server will be created.
	// Addr will always be overwritten, so will the handler.
	Server: &http.Server{},
	// Default handler to use when no route is found.
	// If nil, http.NotFound will be used.
	NotFoundHandler: nil,
}

func main(){
    // Initialize the router
    var SessionStore = scs.New()
    var r = router.NewRouter(nil)

    // Use middleware
    r.Use(middleware.Printer)

    // Custom remade middleware for alexedwards/scs!
    // The regular loadandsave method does not work.
    r.Use(scsmiddleware.SessionMiddleware(SessionStore))

    // Register URLs
    r.Get("/", indexFunc, "index")
    r.Get("/variable/<<name:string>>/<<id:int>>", variableFunc, "variable")

    // Register groups of URLs
    var group = r.Group("/api", "api")
    group.Get("/json", defaultJSONFunc, "json")
    group.Post("/json2", defaultJSONFunc, "json2")
Getting urls, formatting them
    // Find routess by name with the following syntax:
    var index = r.URL(router.ALL, "index")
    var variableRoute = r.URL(router.ALL, "variable")

    // Format the route urls.
    fmt.Println(index.Format())
    fmt.Println(variableRoute.Format("John-Doe", 123))

    // Extra parameters are ignored!
    fmt.Println(variableRoute.Format("John-Doe", 123, 456, 789))

    // Getting child urls
    var json = r.URL(router.ALL, "api:json")
    var json2 = r.URL(router.POST, "api:json2")
    fmt.Println(json.Format())
    fmt.Println(json2.Format())

    // The router is compliant with the http.Handler interface.
    // This means that you can use it as a handler for your own server, 
    // Or serve from the router itself, using the server in the defined config.
    if err := r.Listen(); err != nil {
        fmt.Println(err)
    }
}
Rendering templates

Firstly, we need to define some variables in the router/ templatespackage like so:

    // Configure default template settings.
    templates.TEMPLATEFS = os.DirFS("templates/")
    templates.BASE_TEMPLATE_SUFFIXES = []string{".tmpl"}
    templates.BASE_TEMPLATE_DIRS = []string{"base"}
    templates.TEMPLATE_DIRS = []string{"templates"}
    templates.USE_TEMPLATE_CACHE = false

As you might see from the above code, this follows your file structure.
We do not have to define the regular template directories, but we do have to define the base template directories.
We define the regular directories when rendering them.

    # The base directory is where the base templates are stored.
    templates/
    ├── base
    │   └── base.tmpl
    └── app
        ├── index.tmpl
        └── user.tmpl

Then, we can render templates like so:

func indexFunc(req *request.Request) {
    // Render the template with the given data.
    var err = req.Render("app/index.tmpl")
	if err != nil {
		req.WriteString(err.Error())
	}
}

Documentation

Index

Constants

View Source
const (
	GET     = "GET"
	POST    = "POST"
	PUT     = "PUT"
	DELETE  = "DELETE"
	PATCH   = "PATCH"
	OPTIONS = "OPTIONS"
	HEAD    = "HEAD"

	// Special method for matching all methods
	ALL = "ALL"
)

HTTP Methods

Variables

This section is empty.

Functions

func RedirectWithNextURL

func RedirectWithNextURL(r *request.Request, nextURL string)

Redirect user to a URL, appending the current URL as a "next" query parameter

func ToHTTPHandler

func ToHTTPHandler(h Handler) http.Handler

Make a new http.Handler from a Handler

func WalkRoutes

func WalkRoutes(route *Route, f func(*Route, int))

Recurse over a routes children, keeping track of depth

Types

type ErrorHandlerMiddleware added in v3.2.6

type ErrorHandlerMiddleware func(error, *request.Request) Middleware

type HandleFunc

type HandleFunc func(*request.Request)

HandleFunc is the function that is called when a route is matched

func HTTPWrapper

func HTTPWrapper(handler func(http.ResponseWriter, *http.Request)) HandleFunc

Wrapper function for http.Handler to make it compatible with HandleFunc

func (HandleFunc) ServeHTTP

func (f HandleFunc) ServeHTTP(r *request.Request)

type Handler

type Handler interface {
	ServeHTTP(*request.Request)
}

Handler is the interface that wraps the ServeHTTP method.

func FromHTTPHandler

func FromHTTPHandler(h http.Handler) Handler

Make a new handler from a http.Handler

func NewFSHandler added in v3.3.7

func NewFSHandler(static_url string, fs fs.FS) Handler

type Middleware

type Middleware func(Handler) Handler

Middleware is the function that is called when a route is matched

type Registrar

type Registrar interface {
	// Put registers a new route with the given path and method.
	Put(path string, handler Handler, name ...string) Registrar

	// Post registers a new route with the given path and method.
	Post(path string, handler Handler, name ...string) Registrar

	// Get registers a new route with the given path and method.
	Get(path string, handler Handler, name ...string) Registrar

	// Delete registers a new route with the given path and method.
	Delete(path string, handler Handler, name ...string) Registrar

	// Patch registers a new route with the given path and method.
	Patch(path string, handler Handler, name ...string) Registrar

	// Options registers a new route with the given path and method.
	Options(path string, handler Handler, name ...string) Registrar

	// Head registers a new route with the given path and method.
	Head(path string, handler Handler, name ...string) Registrar

	// Register a route for all methods
	Any(path string, handler Handler, name ...string) Registrar

	// HandleFunc registers a new route with the given path and method.
	HandleFunc(method, path string, handler Handler, name ...string) Registrar

	// Handle is a convenience method that wraps the http.Handler in a HandleFunc
	Handle(method, path string, handler http.Handler) Registrar

	// Use adds middleware to the router.
	Use(middlewares ...Middleware)

	// Group creates a new router URL group
	Group(path string, name string, middlewares ...Middleware) Registrar

	// Addgroup adds a group of routes to the router
	AddGroup(group Registrar)

	// URL returns the URL for a named route
	URL(method, name string) routevars.URLFormatter

	// Call the route, returning the response and a possible error.
	Call(request *http.Request, args ...any) (*http.Response, error)

	// Invoke the route's handler, writing to a response writer.
	Invoke(dest http.ResponseWriter, req *http.Request, args ...any)

	// Returns the formatted URL for this route.
	//
	// If no arguments are provided it will return the path as it is set on the route.
	// This means it will be returned as /my/blog/<<post_id:int>>
	Format(args ...any) string
}

Registrar is the main interface for registering routes

func Group

func Group(path string, name string) Registrar

Group creates a new router URL group

func NewFSRoute added in v3.3.1

func NewFSRoute(static_url string, name string, fs fs.FS) Registrar

func NewRoute added in v3.3.5

func NewRoute(method, path string, name string, handler HandleFunc) Registrar

NewRoute creates a new url group with a handler registered to it.

type Route

type Route struct {
	Method      string
	Path        routevars.URLFormatter
	HandlerFunc Handler
	// contains filtered or unexported fields
}

Route is a single route in the router

func (*Route) AddGroup

func (r *Route) AddGroup(group Registrar)

Add a group to the route

func (*Route) Any

func (r *Route) Any(path string, handler Handler, name ...string) Registrar

Register a route for all methods

func (*Route) Call added in v3.1.7

func (r *Route) Call(req *http.Request, args ...any) (*http.Response, error)

Call a route handler with the given request.

Do so by making a HTTP request to the route's url.

If te url takes arguments, you need to pass them into Call.

It will run the route's middleware and the route's handler.

This will

func (*Route) Delete

func (r *Route) Delete(path string, handler Handler, name ...string) Registrar

Delete registers a new route with the given path and method.

func (*Route) DisableMiddleware

func (r *Route) DisableMiddleware()

Disable the router's middlewares for this route, and all its children It will however still run the route's own middlewares.

func (*Route) Format added in v3.3.9

func (r *Route) Format(args ...any) string

Returns the formatted URL for this route.

If no arguments are provided it will return the path as it is set on the route. This means it will be returned as /my/blog/<<post_id:int>>

func (*Route) Get

func (r *Route) Get(path string, handler Handler, name ...string) Registrar

Get registers a new route with the given path and method.

func (*Route) Group

func (r *Route) Group(path string, name string, middlewares ...Middleware) Registrar

Group creates a new group of routes

func (*Route) Handle

func (r *Route) Handle(method, path string, handler http.Handler) Registrar

Handle is a convenience method that wraps the http.Handler in a HandleFunc

func (*Route) HandleFunc

func (r *Route) HandleFunc(method, path string, handler Handler, name ...string) Registrar

HandleFunc registers a new route with the given path and method.

func (*Route) Head

func (r *Route) Head(path string, handler Handler, name ...string) Registrar

Head registers a new route with the given path and method.

func (*Route) Invoke added in v3.1.7

func (r *Route) Invoke(dest http.ResponseWriter, req *http.Request, args ...any)

Invoke a route handler directly.

If te url takes arguments, you need to pass them into Invoke.

It will not run the route's middleware.

func (*Route) Match

func (r *Route) Match(method, path string) (bool, *Route, params.URLParams)

Match checks if the given path matches the route

func (*Route) Name

func (r *Route) Name() string

Return the name of the route This can be used to match a route with the URL method

func (*Route) Options

func (r *Route) Options(path string, handler Handler, name ...string) Registrar

Options registers a new route with the given path and method.

func (*Route) Patch

func (r *Route) Patch(path string, handler Handler, name ...string) Registrar

Patch registers a new route with the given path and method.

func (*Route) Post

func (r *Route) Post(path string, handler Handler, name ...string) Registrar

Post registers a new route with the given path and method.

func (*Route) Put

func (r *Route) Put(path string, handler Handler, name ...string) Registrar

Put registers a new route with the given path and method.

func (*Route) URL added in v3.0.5

func (r *Route) URL(method, name string) routevars.URLFormatter

URL matches a URL for the given names delimited by a colon. Example:

Parent:Child:GrandChild

func (*Route) Use

func (r *Route) Use(middlewares ...Middleware)

Use adds middleware to the route

type Router

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

Router is the main router struct It takes care of dispatching requests to the correct route

func NewRouter

func NewRouter(skipTrailingSlash bool) *Router

NewRouter creates a new router

func (*Router) AddGroup

func (r *Router) AddGroup(group Registrar)

Addgroup adds a group of routes to the router

func (*Router) Any

func (r *Router) Any(path string, handler Handler, name ...string) Registrar

Register a route for all methods

func (*Router) Delete

func (r *Router) Delete(path string, handler Handler, name ...string) Registrar

Delete registers a new route with the given path and method.

func (*Router) Get

func (r *Router) Get(path string, handler Handler, name ...string) Registrar

Get registers a new route with the given path and method.

func (*Router) Group

func (r *Router) Group(path string, name string, middlewares ...Middleware) Registrar

Group creates a new router URL group

func (*Router) Handle

func (r *Router) Handle(method, path string, handler http.Handler) Registrar

Handle is a convenience method that wraps the http.Handler in a HandleFunc

func (*Router) HandleFunc

func (r *Router) HandleFunc(method, path string, handler Handler, name ...string) Registrar

HandleFunc registers a new route with the given path and method.

func (*Router) Head

func (r *Router) Head(path string, handler Handler, name ...string) Registrar

Head registers a new route with the given path and method.

func (*Router) Match

func (r *Router) Match(method, path string) (bool, *Route, params.URLParams)

Match returns the route that matches the given method and path.

func (*Router) Options

func (r *Router) Options(path string, handler Handler, name ...string) Registrar

Options registers a new route with the given path and method.

func (*Router) Patch

func (r *Router) Patch(path string, handler Handler, name ...string) Registrar

Patch registers a new route with the given path and method.

func (*Router) Post

func (r *Router) Post(path string, handler Handler, name ...string) Registrar

Post registers a new route with the given path and method.

func (*Router) Put

func (r *Router) Put(path string, handler Handler, name ...string) Registrar

Put registers a new route with the given path and method.

func (*Router) ServeHTTP

func (r *Router) ServeHTTP(w http.ResponseWriter, rq *http.Request)

ServeHTTP dispatches the request to the handler whose pattern matches the request URL.

func (*Router) String added in v3.2.7

func (r *Router) String() string

Returns all the routes in a nicely formatted string for debugging.

func (*Router) URL

func (r *Router) URL(method, name string) routevars.URLFormatter

Get a route by name.

Route names are optional, when used a route's child can be access like so:

It looks like Django's URL routing syntax.

router.Route("routeName")

router.Route("parentName:routeToGet")

func (*Router) URLFormat

func (r *Router) URLFormat(name string, args ...interface{}) string

The URL func, but for easy use in templates.

It returns the URL, formatted based on the arguments.

func (*Router) Use

func (r *Router) Use(middlewares ...Middleware)

Use adds middleware to the router.

type Vars

type Vars map[string]string

Variable map passed to the route.

Jump to

Keyboard shortcuts

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