router

package module
v0.0.0-...-836ce8a Latest Latest
Warning

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

Go to latest
Published: Sep 30, 2019 License: MIT Imports: 20 Imported by: 0

README

ZAPPWORK - Go Router

codecov.io Go Report Card Build Status GoDoc

Installation

The current stable release is 0.8.1. This is a breaking release with 0.7., 0.6. and 0.5. No more breaking changes will be added before final release.

Major changes in 0.8.0:

  • Add multiple routers
  • Route groups
  • Additional request information methods
  • Custom logger
  • bug fixes
go get bitbucket.org/zappwork/router

Documentation

After installation run the following command in your terminal

Find documentation at GoDoc

godoc -http=:6060

and open the following url in your browser http://localhost:6060/pkg/bitbucket.org/zappwork/router/

Usage

Usage is simple and easy to set up.

  • Serve static files
  • Serve static folder
  • Routing
    • Custom HTTP Method
    • Generic routing
    • Grouped routes
    • Parameter routing
    • Catch routes
  • Middleware (Use Globally, Grouped or on a route individualy)
  • Logger
  • NotFound
  • Error
Serve Static Files

You have the ability to serve single static files from any location. If you have only a few files this is the preferred route.

Directory structure

app
├── main.go
├── assets
|   ├── index.html
|   ├── favicon.ico
|   ├── css
|   |   └── styles.css
|   ├── js
|   |   └── main.js
|   ├── img
|   |   └── logo.png

main.go

package main

import (
	"bitbucket.org/zappwork/router"
)

func main() {
	rt := router.NewRouter(nil)
	rt.StaticFile("/",             "./assets/index.html")
	rt.StaticFile("/favicon.ico",  "./assets/favicon.ico")
	rt.StaticFile("/css/site.css", "./assets/css/styles.css")
	rt.StaticFile("/js/site.js",   "./assets/js/main.js")
	rt.StaticFile("/img/site.png", "./assets/img/logo.png")
	rt.Start(nil, true)
}

Now your files are being served.

Serve Static Folders

You have the ability to serve static files from folders from any location. If you have only a few a lot of static files this is the preferred route.

Directory structure

app
├── main.go
├── assets
|   ├── index.html
|   ├── favicon.ico
|   ├── css
|   |	└── site.css
|   |	└── print.css
|   |	└── screen.css
|   ├── js
|   |	└── main.js
|   |	└── tools.js
|   |	└── mobile.js
|   ├── img
|   |	└── logo.png
|   |	└── logo-large.png
|   |	└── gallery-1.png
|   |	└── gallery-2.png
|   |	└── gallery-3.png

main.go

package main

import (
	"bitbucket.org/zappwork/router"
)

func main() {
	rt := router.NewRouter(nil)
	rt.StaticFile("/",             "./assets/index.html")
	rt.StaticFile("/favicon.ico",  "./assets/favicon.ico")
	rt.StaticFolder("/css/",       "./assets/css/")
	rt.StaticFolder("/js/",        "./assets/js/")
	rt.StaticFolder("/img/",       "./assets/img/")
	rt.Start(router.NewConfig(), true)
}

Any file in the folder will be served without the need to change your code.

Routing

You do not want to use Go just for serving static files. Use the easy and efficient routing and map the requests easily for the HTTP request methods (e.g. GET, POST, PUT, DELETE, OPTIONS or HEAD). If no match is found for static files and routes then a 404 will be automatically generated.

Custom HTTP Method

Not all HTTP request methods are supported by all programming languages. That is why there are a few ways to fake an HTTP request method.

Header X-HTTP-Method-Override Sometimes the "X-HTTP-Method-Override" header is used for the unsupported request method.

Post/Form Value Another way to override the request method is through the "_METHOD" post/form value.

The zappwork router supports this ways of sending the request method.

Generic routing

Routing functions

// Catch request for file.html and request method GET
rt.Get("/file.html", func(r *router.RouteRequest) (err *router.Error) {
	fmt.Fprintf(r.Writer(), r.Method()+" "+r.Path())
	return
})
// Catch request for file.html and request method POST
rt.Post("/file.html", func(r *router.RouteRequest) (err *router.Error) {
	fmt.Fprintf(r.Writer(), r.Method()+" "+r.Path())
	return
})
// Catch request for file.html and request method PUT
rt.Put("/file.html", func(r *router.RouteRequest) (err *router.Error) {
	fmt.Fprintf(r.Writer(), r.Method()+" "+r.Path())
	return
})
// Catch request for file.html and request method DELETE
rt.Delete("/file.html", func(r *router.RouteRequest) (err *router.Error) {
	fmt.Fprintf(r.Writer(), r.Method()+" "+r.Path())
	return
})
// Catch request for file.html and request method OPTIONS
rt.Options("/file.html", func(r *router.RouteRequest) (err *router.Error) {
	fmt.Fprintf(r.Writer(), r.Method()+" "+r.Path())
	return
})
// Catch request for file.html and request method PATCH
rt.Patch("/file.html", func(r *router.RouteRequest) (err *router.Error) {
	fmt.Fprintf(r.Writer(), r.Method()+" "+r.Path())
	return
})

main.go

package main

import (
	"fmt"
	"bitbucket.org/zappwork/router"
)

func main() {
	rt := router.NewRouter(nil)
	rt.Get("/", echo)
	rt.Get("/folder/", echo)
	rt.Get("/another/folder/", echo)
	rt.Get("/another/folder/hello.html", echo)
	rt.Start(router.NewConfig(), true)
}

// echo simple information
func echo(r *router.RouteRequest) (err *router.Error) {
	fmt.Fprintf(r.Writer(), r.Method()+" "+r.Path())
	return
}

Now the paths are served through the router and will return the given information.

Parameter routing

It is also possible to add named routes with parameters in it. The parameters are returned in the RouteRequest object and can be used.

main.go

package main

import (
	"fmt"
	"bitbucket.org/zappwork/router"
)

func main() {
	rt := router.NewRouter(nil)
	rt.Get("/{name}.html", echo)
	rt.Get("/folder/{name}.html", echo)
	rt.Get("/another/{name}/", echo)
	rt.Get("/another/folder/{name}.html", echo)
	rt.Start(router.NewConfig(), true)
}

// echo simple information
func echo(r *router.RouteRequest) (err *router.Error) {
	name, _ := r.PathArg("name")
	fmt.Fprintf(r.Writer(), r.Method()+" "+r.Path()+" "+name)
	return
}

Now the paths are served through the router and will return the given information.

Catch routes

Catch a route independant of the HTTP request method. First matches will be made to the specified request method and then the routes in the catch will be matched.

main.go

package main

import (
	"fmt"
	"bitbucket.org/zappwork/router"
)

func main() {
	rt := router.NewRouter(nil)
	rt.Get("/{name}.html", echo)
	rt.Catch("/{name}.html", echo)
	rt.Start(router.NewConfig(), true)
}

// echo simple information
func echo(r *router.RouteRequest) (err *router.Error) {
	name, _ := r.PathArg("name")
	fmt.Fprintf(r.Writer(), r.Method()+" "+r.Path()+" "+name)
	return
}

Everything except the GET requests are processed by catch call.

Middleware

It is also possible to add middleware for route pre-processing. The middeware can be added in with use function and requests can be manipulated and are used for route matching an processing. This functionality can be used for:

  • Authentication
  • URL rewriting
  • Logging
  • ...

main.go

package main

import (
	"fmt"
	"log"
	"net/http"
	"bitbucket.org/zappwork/router"
)

func main() {
	rt := router.NewRouter(nil)
	rt.Get("/{name}.html", echo)
	rt.Catch("/{name}.html", echo)
	rt.Use(rewrite)
	rt.Start(router.NewConfig(), true)
}

// echo simple information
func echo(r *router.RouteRequest) (err *router.Error) {
	name, _ := r.PathArg("name")
	fmt.Fprintf(r.Writer(), r.Method()+" "+r.Path()+" "+name)
	return
}

// log simple information
func logger(r *router.RouteRequest) error {
	log.Println(r.Path(), " - ", r.Method())
	return nil
}

// Rewrite path
func rewrite(r *router.RouteRequest) error {
	r.Request().URL.Path = "/rewritten.html"
	return nil
}
Logger

You are able to change the logging of the router and the custom logger should have the Logger interface.

// This is the default logger
rt.SetLogger(router.DefaultLogger{})
404 Not Found

If a path is not matched in any way there will always be a standard 404 return from the router. The standard 404 can be overwritten with a custom 404 handler. The 404 status is return automatically.

package main

import (
	"fmt"
	"net/http"
	"bitbucket.org/zappwork/router"
)

func main() {
	rt := router.NewRouter(nil)
	rt.Get("/{name}.html", echo)
	rt.Catch("/{name}.html", echo)
	rt.AddNotFoundHandler(notfound)
	rt.Start(router.NewConfig(), true)
}

// echo simple information
func echo(r *router.RouteRequest) (err *router.Error) {
	name, _ := r.PathArg("name")
	fmt.Fprintf(r.Writer(), r.Method()+" "+r.Path()+" "+name)
	return
}

// Simple 404 handler
func notfound(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf("I do not exist!")
}
500 Error

If an err was returned in one of the routing calls a standard server error was generated. This can also be overwritten in the router. A status 500 is automatically generated by the system.

package main

import (
	"fmt"
	"errors"
	"net/http"
	"bitbucket.org/zappwork/router"
)

func main() {
	rt := router.NewRouter(nil)
	rt.Get("/{name}.html", echo)
	rt.Catch("/{name}.html", echo)
	rt.AddErrorHandler(errorhandler)
	rt.Start(router.NewConfig(), true)
}

// echo simple information
func echo(r *router.RouteRequest) (err *router.Error) {
	return errors.New("Something went wrong!")
}

// Simple error handler
func errorhandler(w http.ResponseWriter, r *http.Request, errors ...error) {
	fmt.Fprintf("What went wrong")
}
Custom Start & Stop output/function

Override the default start and stop output

package main

import (
	"fmt"
	"errors"
	"net/http"
	"bitbucket.org/zappwork/router"
)

func main() {
	rt := router.NewRouter(nil)
	rt.Get("/{name}.html", echo)
	rt.Catch("/{name}.html", echo)
	rt.OnStart = func() {
		log.Println("Router started")
	}
	router.OnStop = func(message string) {
		log.Println("Router stopped with", message)
	}
	rt.Start(router.NewConfig(), true)
}

// echo simple information
func echo(r *router.RouteRequest) (err *router.Error) {
	name, _ := r.PathArg("name")
	fmt.Fprintf(r.Writer(), r.Method()+" "+r.Path()+" "+name)
	err = errors.New("Something went wrong!")
	return
}

// Simple 404 handler
func errorhandler(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf("What went wrong")
}

Documentation

Overview

Package router The zappwork Golang router and is an easy to use router with pre/post processing middleware.

Serving static files

Serving static files is easy, see the example below.

package main
import (
	"bitbucket.org/zappwork/router"
)
func main() {
	rt := NewRouter(nil)
	rt.StaticFile("/",             "./assets/index.html")
	rt.StaticFile("/favicon.ico",  "./assets/favicon.ico")
	rt.StaticFolder("/css/",       "./assets/css/")
	rt.StaticFolder("/js/",        "./assets/js/")
	rt.StaticFolder("/img/",       "./assets/img/")
	rt.Start(nil)
}

Some examples of how to use the routing

Catch request for file.html and request method GET

rt.Get("/file.html", func(r router.RouteRequest) (err *router.Error) {
	fmt.Fprintf(r.Writer(), r.Method()+" "+r.Path())
	return
})

Catch request for file.html and request method POST

rt.Post("/file.html", func(r router.RouteRequest) (err *router.Error) {
	fmt.Fprintf(r.Writer(), r.Method()+" "+r.Path())
	return
})

Catch request for file.html and request method PUT

rt.Put("/file.html", func(r router.RouteRequest) (err *router.Error) {
	fmt.Fprintf(r.Writer(), r.Method()+" "+r.Path())
	return
})

Catch request for file.html and request method DELETE

rt.Delete("/file.html", func(r router.RouteRequest) (err *router.Error) {
	fmt.Fprintf(r.Writer(), r.Method()+" "+r.Path())
	return
})

Catch request for file.html and request method OPTIONS

rt.Options("/file.html", func(r router.RouteRequest) (err *router.Error) {
	fmt.Fprintf(r.Writer(), r.Method()+" "+r.Path())
	return
})

Catch request for file.html and request method PATCH

rt.Patch("/file.html", func(r router.RouteRequest) (err *router.Error) {
	fmt.Fprintf(r.Writer(), r.Method()+" "+r.Path())
	return
})

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ParseRemoteAddr

func ParseRemoteAddr(r *http.Request) (ipAddr string)

ParseRemoteAddr parse a remoteAddr to a human readable ip address

Types

type Config

type Config struct {
	Host             string
	Port             int
	StaticTimeout    int
	RequestTimeout   time.Duration
	TimeoutMessage   string
	Logging          bool
	Verbose          bool
	ShowSystemInfo   bool
	CorsEnabled      bool
	CorsAllowOrigin  string
	CorsAllowHeaders string
	CorsAllowMethods string
}

Config foro router package

func NewConfig

func NewConfig() *Config

NewConfig initialise a config object

func (*Config) HostString

func (c *Config) HostString() string

HostString get the host string for the server

func (*Config) Strings

func (c *Config) Strings() []string

Strings get the strings of the config

type DefaultLogger

type DefaultLogger struct{}

DefaultLogger is the default logger

func (DefaultLogger) Debug

func (d DefaultLogger) Debug(args ...interface{})

Debug logs debug information

func (DefaultLogger) Debugf

func (d DefaultLogger) Debugf(format string, args ...interface{})

Debugf logs information

func (DefaultLogger) Error

func (d DefaultLogger) Error(args ...interface{})

Error logs error information

func (DefaultLogger) Errorf

func (d DefaultLogger) Errorf(format string, args ...interface{})

Errorf logs information

func (DefaultLogger) Info

func (d DefaultLogger) Info(args ...interface{})

Info logs information

func (DefaultLogger) Infof

func (d DefaultLogger) Infof(format string, args ...interface{})

Infof logs information

func (DefaultLogger) Request

func (d DefaultLogger) Request(uuid, method, path string, status int, duration, ip, useragent string, err *Error)

Request logs the router request

type Error

type Error struct {
	Code    int
	Message string
}

Error generic router error

func FromError

func FromError(err error) *Error

FromError makes a router error form a regular error

func NewError

func NewError(code int, message string) *Error

NewError return an initialized pointer to an a router error

func NewJSONError

func NewJSONError(code int, message interface{}) *Error

NewJSONError returns an initialized error where the message interface is marshalled as and json string

func (Error) Error

func (e Error) Error() error

Error returns a error representation of the router error

func (Error) String

func (e Error) String() string

String returns a string representation of the error

type Func

type Func func(*RouteRequest) *Error

Func is the generic router function used in the application

type Logger

type Logger interface {
	Request(string, string, string, int, string, string, string, *Error)
	Info(args ...interface{})
	Infof(format string, args ...interface{})
	Error(args ...interface{})
	Errorf(format string, args ...interface{})
	Debug(args ...interface{})
	Debugf(format string, args ...interface{})
}

Logger interface

type PostMap

type PostMap map[string]string

The PostMap type

type RouteGroup

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

RouteGroup is grouping routes

func NewGroup

func NewGroup(path string) *RouteGroup

NewGroup returns a point to a route group

func (*RouteGroup) Catch

func (g *RouteGroup) Catch(path string, f Func, use ...Func) *RouteGroup

Catch a route independent of the request method and specify the handling function and/or controller

func (*RouteGroup) Delete

func (g *RouteGroup) Delete(path string, f Func, use ...Func) *RouteGroup

Delete add a new route DELETE route to the router and specify the handling function and/or controller

func (*RouteGroup) Get

func (g *RouteGroup) Get(path string, f Func, use ...Func) *RouteGroup

Get add a new route GET route to the router and specify the handling function and/or controller

func (*RouteGroup) Group

func (g *RouteGroup) Group(gr *RouteGroup) *RouteGroup

Group add a grouped route on the given path

func (*RouteGroup) Options

func (g *RouteGroup) Options(path string, f Func, use ...Func) *RouteGroup

Options add a new route OPTIONS route to the router and specify the handling function and/or controller

func (*RouteGroup) Patch

func (g *RouteGroup) Patch(path string, f Func, use ...Func) *RouteGroup

Patch add a new route PATCH route to the router and specify the handling function and/or controller

func (*RouteGroup) Path

func (g *RouteGroup) Path() string

Path get the group path

func (*RouteGroup) Post

func (g *RouteGroup) Post(path string, f Func, use ...Func) *RouteGroup

Post add a new route POST route to the router and specify the handling function and/or controller

func (*RouteGroup) Put

func (g *RouteGroup) Put(path string, f Func, use ...Func) *RouteGroup

Put add a new route PUT route to the router and specify the handling function and/or controller

func (*RouteGroup) SetPath

func (g *RouteGroup) SetPath(path string)

SetPath set the group path

func (*RouteGroup) Use

func (g *RouteGroup) Use(f ...Func) *RouteGroup

Use add middleware specific for this group

type RouteRequest

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

RouteRequest struct used in the handler function

func (*RouteRequest) Accept

func (rr *RouteRequest) Accept() string

Accept returns the type of response requested

func (*RouteRequest) AddHeader

func (rr *RouteRequest) AddHeader(name, value string)

AddHeader to the response

func (*RouteRequest) AskAuthentication

func (rr *RouteRequest) AskAuthentication(realm string)

AskAuthentication ask credentials for the given realm

func (*RouteRequest) Context

func (rr *RouteRequest) Context(key string) interface{}

Context gets a context key value pairing

func (*RouteRequest) Cookie

func (rr *RouteRequest) Cookie(name string) (*http.Cookie, error)

Cookie returns the named cookie provided in the request or ErrNoCookie if not found

func (*RouteRequest) Cookies

func (rr *RouteRequest) Cookies() []*http.Cookie

Cookies parses and returns the HTTP cookies sent with the request

func (*RouteRequest) Credentials

func (rr *RouteRequest) Credentials() (user, password string, ok bool)

Credentials get the credetials for authentication

func (*RouteRequest) Domain

func (rr *RouteRequest) Domain() string

Domain return the tld for the current host

func (*RouteRequest) HasQueryParam

func (rr *RouteRequest) HasQueryParam(key string) bool

HasQueryParam does the request have a query param

func (*RouteRequest) Header

func (rr *RouteRequest) Header(h string) string

Header get a request header

func (*RouteRequest) Host

func (rr *RouteRequest) Host() string

Host get the Host value

func (*RouteRequest) IPAddress

func (rr *RouteRequest) IPAddress() string

IPAddress get the remote IP and port used

func (*RouteRequest) Method

func (rr *RouteRequest) Method() string

Method get the response writer to handle the response

func (*RouteRequest) Path

func (rr *RouteRequest) Path() string

Path get the request path

func (*RouteRequest) PathArg

func (rr *RouteRequest) PathArg(key string) (arg string, ok bool)

PathArg get the route/path arguments which were dynamic. They are key/value pair and can be retrieved through this function

func (*RouteRequest) PathArgAsBool

func (rr *RouteRequest) PathArgAsBool(key string) (bool, bool)

PathArgAsBool get the post params posted in the from. They are key/value pair and can be retrieved through this function

func (*RouteRequest) PathArgAsInt

func (rr *RouteRequest) PathArgAsInt(key string) (int, bool)

PathArgAsInt get the post params posted in the from. They are key/value pair and can be retrieved through this function

func (*RouteRequest) PathArgAsInt64

func (rr *RouteRequest) PathArgAsInt64(key string) (arg int64, ok bool)

PathArgAsInt64 get the route/path arguments which were dynamic. They are key/value pair and can be retrieved through this function

func (*RouteRequest) PostArrayMap

func (rr *RouteRequest) PostArrayMap(key string) (arg map[int]PostMap, ok bool)

PostArrayMap get the post ArrayMap posted in the from. They are int -> key/value pair and can be retrieved through this function

func (*RouteRequest) PostMap

func (rr *RouteRequest) PostMap(key string) (arg PostMap, ok bool)

PostMap get the post ArrayMap posted in the from. They are key/value pair and can be retrieved through this function

func (*RouteRequest) PostMultiValue

func (rr *RouteRequest) PostMultiValue(key string) ([]string, bool)

PostMultiValue get the post params posted in the from. They are key/value pair and can be retrieved through this function

func (*RouteRequest) PostValue

func (rr *RouteRequest) PostValue(key string) (string, bool)

PostValue get the post params posted in the from. They are key/value pair and can be retrieved through this function

func (*RouteRequest) PostValueAsBool

func (rr *RouteRequest) PostValueAsBool(key string) (bool, bool)

PostValueAsBool get the post params posted in the from. They are key/value pair and can be retrieved through this function

func (*RouteRequest) PostValueAsFloat64

func (rr *RouteRequest) PostValueAsFloat64(key string) (float64, bool)

PostValueAsFloat64 get the post params posted in the from. They are key/value pair and can be retrieved through this function

func (*RouteRequest) PostValueAsInt

func (rr *RouteRequest) PostValueAsInt(key string) (int, bool)

PostValueAsInt get the post params posted in the from. They are key/value pair and can be retrieved through this function

func (*RouteRequest) PostValueAsInt64

func (rr *RouteRequest) PostValueAsInt64(key string) (int64, bool)

PostValueAsInt64 get the post params posted in the form

func (*RouteRequest) QueryParam

func (rr *RouteRequest) QueryParam(key string) (string, bool)

QueryParam get the query params as given in the url. They are key/value pair and can be retrieved through this function

func (*RouteRequest) QueryParamAsBool

func (rr *RouteRequest) QueryParamAsBool(key string) (bool, bool)

QueryParamAsBool get query param as an float64

func (*RouteRequest) QueryParamAsFloat64

func (rr *RouteRequest) QueryParamAsFloat64(key string) (float64, bool)

QueryParamAsFloat64 get query param as an float64

func (*RouteRequest) QueryParamAsInt64

func (rr *RouteRequest) QueryParamAsInt64(key string) (int64, bool)

QueryParamAsInt64 get query param as an int64

func (*RouteRequest) QueryParamAsSlice

func (rr *RouteRequest) QueryParamAsSlice(key, seperator string) (s []string, ok bool)

QueryParamAsSlice get query param as an float64

func (*RouteRequest) QueryParamAsTime

func (rr *RouteRequest) QueryParamAsTime(key, layout string) (*time.Time, bool)

QueryParamAsTime get query param as a time.Time

func (*RouteRequest) QueryParamAsUint64

func (rr *RouteRequest) QueryParamAsUint64(key string) (uint64, bool)

QueryParamAsUint64 get query param as an uint64

func (*RouteRequest) RawPostBytes

func (rr *RouteRequest) RawPostBytes() (data []byte, err error)

RawPostBytes get posted body as a string.

func (*RouteRequest) RawPostString

func (rr *RouteRequest) RawPostString() (data string, err error)

RawPostString get posted body as a byte slice.

func (*RouteRequest) ReadJSON

func (rr *RouteRequest) ReadJSON(v interface{}) (err error)

ReadJSON get the raw Json information

func (*RouteRequest) ReadXML

func (rr *RouteRequest) ReadXML(v interface{}) (err error)

ReadXML get Unmarshal posted json into an interface.

func (*RouteRequest) Redirect

func (rr *RouteRequest) Redirect(path string, permanent bool)

Redirect from RouteRequest to the given path

func (*RouteRequest) Request

func (rr *RouteRequest) Request() *http.Request

Request get the original call request. This should not be needed for regular requests, but can be used if needed.

func (*RouteRequest) SetContext

func (rr *RouteRequest) SetContext(key string, value interface{})

SetContext sets a context key value pairing

func (*RouteRequest) SetCookie

func (rr *RouteRequest) SetCookie(cookie *http.Cookie)

SetCookie adds a Set-Cookie header to the provided ResponseWriter's headers

func (*RouteRequest) SetStatusCode

func (rr *RouteRequest) SetStatusCode(code int)

SetStatusCode set the return status code

func (*RouteRequest) StatusCode

func (rr *RouteRequest) StatusCode() int

StatusCode get the status code

func (*RouteRequest) UnmarshalRawPost

func (rr *RouteRequest) UnmarshalRawPost(v interface{}) (err error)

UnmarshalRawPost get Unmarshal posted json into an interface.

func (*RouteRequest) Write

func (rr *RouteRequest) Write(s string) (err *Error)

Write interface as JSON to client

func (*RouteRequest) WriteBuffer

func (rr *RouteRequest) WriteBuffer(b *bytes.Buffer) (err *Error)

WriteBuffer write bytes buffer to client

func (*RouteRequest) WriteBytes

func (rr *RouteRequest) WriteBytes(b []byte) (err *Error)

WriteBytes write bytes to client

func (*RouteRequest) WriteJSON

func (rr *RouteRequest) WriteJSON(v interface{}) (err *Error)

WriteJSON write interface as JSON to client

func (*RouteRequest) WriteStatusCode

func (rr *RouteRequest) WriteStatusCode(code int)

WriteStatusCode set write the status code

func (*RouteRequest) WriteXML

func (rr *RouteRequest) WriteXML(v interface{}) (err *Error)

WriteXML write interface as XML to client

func (*RouteRequest) Writer

func (rr *RouteRequest) Writer() http.ResponseWriter

Writer get the response writer to handle the response

type Router

type Router struct {

	// Unique number for the current router
	UUID string

	// OnStart custom start funcion else the default start message will be displayed
	OnStart func()
	// OnStop custom stop function else the default stop message will be displayed
	OnStop func(string)
	// contains filtered or unexported fields
}

Router is a new Router instance

func NewRouter

func NewRouter(c *Config) *Router

NewRouter return initialized router

func (*Router) AddCatchAllHandler

func (r *Router) AddCatchAllHandler(handler Func)

AddCatchAllHandler add a catch all unhandeled router to the router.

func (*Router) AddErrorHandler

func (r *Router) AddErrorHandler(handler func(http.ResponseWriter, *http.Request, *Error))

AddErrorHandler add custom error handler. This will enable you to show custom 500 error pages.

func (*Router) AddNotFoundHandler

func (r *Router) AddNotFoundHandler(handler Func)

AddNotFoundHandler add a custom NotFound handler to the router. This will enable you serve custom 404 pages.

func (*Router) Catch

func (r *Router) Catch(path string, f Func, use ...Func) *Router

Catch a route independent of the request method and specify the handling function and/or controller

func (*Router) Delete

func (r *Router) Delete(path string, f Func, use ...Func) *Router

Delete add a new route DELETE route to the router and specify the handling function and/or controller

func (*Router) Get

func (r *Router) Get(path string, f Func, use ...Func) *Router

Get add a new route GET route to the router and specify the handling function and/or controller

func (*Router) Group

func (r *Router) Group(g *RouteGroup) *Router

Group add a grouped route on the given path

func (*Router) Handler

func (r *Router) Handler() (handler http.Handler)

Handler return the http.Handler for the router

func (*Router) Options

func (r *Router) Options(path string, f Func, use ...Func) *Router

Options add a new route OPTIONS route to the router and specify the handling function and/or controller

func (*Router) Patch

func (r *Router) Patch(path string, f Func, use ...Func) *Router

Patch add a new route PATCH route to the router and specify the handling function and/or controller

func (*Router) Post

func (r *Router) Post(path string, f Func, use ...Func) *Router

Post add a new route POST route to the router and specify the handling function and/or controller

func (*Router) Put

func (r *Router) Put(path string, f Func, use ...Func) *Router

Put add a new route PUT route to the router and specify the handling function and/or controller

func (*Router) Reset

func (r *Router) Reset()

Reset all routes and validations

func (*Router) SetLogger

func (r *Router) SetLogger(l Logger)

SetLogger sets a custom logging function

func (*Router) Start

func (r *Router) Start(c *Config, keepAlive bool)

Start the router and start listening for connections

func (*Router) StaticFile

func (r *Router) StaticFile(path string, serve string) *Router

StaticFile add a single file to serve through the router.

func (*Router) StaticFolder

func (r *Router) StaticFolder(base string, serve string) *Router

StaticFolder add static folder paths. This should be folders and paths will be cleaned correctly. And example would be: rt.AddStatic("/js/", "./assets/default/js") The first argument is the base path as defined in the html and the seconds is the path to the files on the server.

func (*Router) Stop

func (r *Router) Stop(message string)

Stop the router and display the message

func (*Router) Use

func (r *Router) Use(f Func) *Router

Use add pre route processing. This will enable you to add pre route processing like route rewriting/authentication.

Directories

Path Synopsis
test

Jump to

Keyboard shortcuts

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