router

package module
v0.0.0-...-22de752 Latest Latest
Warning

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

Go to latest
Published: Sep 23, 2021 License: MIT Imports: 14 Imported by: 1

README

simple-router

Simple-router is a request router and dispatcher.

How to install simple-router

go get github.com/starmanmaritn/simple-router

why simple-router

simple-router registers a list of routes with a list of handlers. On incoming requests it matches the route and calls all fitting handler. The call order of the handler is the same order they were registered. A nother feature is the multipart/form-data handler.

Getting started

import (
    "github.com/starmanmaritn/simple-router"
    "github.com/starmanmartin/simple-router/request"
    "net/http"
)

func YourHandler(w http.ResponseWriter, r *request.Request) () {
    w.Write([]byte("Hallo Welt! (German)"))
}

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

    // Routes consist of a path and a handler function.
    r.Get("/world", YourHandler)

    // Bind to a port and pass our router in
    http.ListenAndServe(":8000", r)
}

Here we register one route and run a server on port :8000. The handler YourHandler() gets called on a Get witch matches the path "/world". I.e. "http://localhost:8000/world".

Router instance

There are four different constructor to get a router instance

  • NewRouter()
  • NewSubRouter(base string)
  • NewXHRRouter()
  • NewXHRSubRouter(base string)
Router

NewRouter() and NewXHRRouter(string) return a router. We can register new routes on a router. To register a route we simply call:

  • .Get(path string, handler ...HTTPHandler)
  • .Post(path string, handler ...HTTPHandler)
  • .Del(path string, handler ...HTTPHandler)
  • .Put(path string, handler ...HTTPHandler)
  • .All(path string, handler ...HTTPHandler)

The path allows to add route parameter. "/:name" adds a parameter called "name" to the RouteParams filed at the request instance. It is possibe to use a wildecard in your path with *.

Public file server

To set a public web-folder the router has the method router.Public(path string). The path has two meanings: Firstly it sets the file path, relative to os.Args[0] path. Secondly It register a route to and a file server as handler.

Upload via multipart form

Simply set an upload folder by calling the router.Upload(path string, isBuffer bool) method. The path for the upload folder is relative to theos.Args[0] path. The isBuffer bool sets if the buffer content gets saved to the request or not

Use

To use the usual go handler it is possible to call the .Use(path string, handler ...http.HandlerFunc) function.

To run a server

To run a sever simply pass a router instance to the http.ListenAndServe(":8000", r) function.

Sub-Router

NewSubRouter(string) and NewXHRSubRouter(string) return a sub-router. All routes registerde on a sub-router have the sub-router base as prefix.

// http://localhost:8000/home/less
NewSubRouter("/home").Get("/less", YourHandler)
XHR Router

NewXHRRouter() and NewXHRSubRouter(string) return a normal router or sub-router. The only difference is that only requests where the field 'X-Requested-With' in the header is 'XMLHttpRequest' get served. (jQuery.Get(...) or jQuery.ajax(...)) ''

View

The sub-package "github.com/starmanmartin/simple-router/view" extends the template engine.

var ViewPath string
func ParseTemplate(name, filePath string) (tmp *template.Template)

It easily allows to parse templates. First the ViewPath is the relative path to os.Args[0] and needs to be set. The function ParseTemplate gets a name and a file path relative to the ViewPath path. By adding "<!--extent: filename --&#062;" to the template, the template automatically adds the file form filename to the templateparsing process. To add multiple file simply separate the filenames by ','.

Sample:

views/base.html:

{{define "base"}}
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
</head>
<body>

    <article id="content">
        <div>
            {{template "content" .}}
        </div>
    </article>
</body>

</html>
{{end}}

views/index.html:

<!--extent: base-->
{{define "content"}}
<h1>Index HTML</h1>
{{end}}

In GO:

view.ViewPath = "views"
view.ParseTemplate("index", "index.html")

Tests

import "github.com/starmanmaritn/simple-router/rtest"

The rtest package holds multiple function to generate a mock request. For the sake of testing, the request object is an own package.

Tip

The "net/http/httptest" package provides multible mocks, for example a mocked response writer.

Documentation

Overview

Package router handels theroutiing Author: Maritn Starman

Index

Constants

This section is empty.

Variables

View Source
var (
	// NotFoundHandler function if path not found
	NotFoundHandler func(w http.ResponseWriter, r *request.Request)
	// ErrorHandler reponshandler on Error
	ErrorHandler func(err error, w http.ResponseWriter, r *request.Request)
	// XHRNotFoundHandler function if path not found
	XHRNotFoundHandler func(w http.ResponseWriter, r *request.Request)
	// XHRErrorHandler reponshandler on Error
	XHRErrorHandler func(err error, w http.ResponseWriter, r *request.Request)
)

Functions

This section is empty.

Types

type ByIndex

type ByIndex []*finalRouteElement

ByAge implements sort.Interface for []Person based on the Age field.

func (ByIndex) Len

func (a ByIndex) Len() int

func (ByIndex) Less

func (a ByIndex) Less(i, j int) bool

func (ByIndex) Swap

func (a ByIndex) Swap(i, j int)

type HTTPHandler

type HTTPHandler func(w http.ResponseWriter, r *request.Request) (bool, error)

HTTPHandler defines Type

type Manager

type Manager struct {
	*SubManager
}

Manager instance of router

func NewRouter

func NewRouter() *Manager

NewRouter returns new instance of the Router

func NewXHRRouter

func NewXHRRouter() *Manager

NewXHRRouter returns new instance of the Router

func (*Manager) Public

func (r *Manager) Public(path string) string

Public sets a Fileserver for path

func (*Manager) ServeHTTP

func (r *Manager) ServeHTTP(w http.ResponseWriter, httpR *http.Request)

func (*Manager) UploadPath

func (r *Manager) UploadPath(path string, isBuffer bool) HTTPHandler

UploadPath Registers a upload Path

type SubManager

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

SubManager manages routs in a sub path

func NewSubRouter

func NewSubRouter(root string) *SubManager

NewSubRouter returns new instance of the Router

func NewXHRSubRouter

func NewXHRSubRouter(root string) *SubManager

NewXHRSubRouter returns new instance of the Router

func (*SubManager) All

func (r *SubManager) All(route string, handler ...HTTPHandler)

All register a route for the All methods

func (*SubManager) Delete

func (r *SubManager) Delete(route string, handler ...HTTPHandler)

Delete register a route for the Delete method

func (*SubManager) Get

func (r *SubManager) Get(route string, handler ...HTTPHandler)

Get registers a route for the GET method

func (*SubManager) Post

func (r *SubManager) Post(route string, handler ...HTTPHandler)

Post register a route for the POST method

func (*SubManager) Put

func (r *SubManager) Put(route string, handler ...HTTPHandler)

Put register a route for the Put method

func (*SubManager) Use

func (r *SubManager) Use(route string, handler ...http.HandlerFunc)

Use is to register a api for GET, POST, DELETE,and PUT

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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