gora

package
v0.1.4 Latest Latest
Warning

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

Go to latest
Published: Jan 21, 2023 License: MIT Imports: 31 Imported by: 1

Documentation

Overview

Gora is a package for easily defining and matching routes using regular expressions. Inspired by the Django web framework's powerful routing system, this library allows you to define a set of patterns for your routes and automatically match incoming requests to the appropriate handler. Whether you are building a simple API or a complex web application, this library is a convenient and flexible tool for routing requests in Go.

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrEmptyRequestBody = errors.New("empty request body")
)
View Source
var ErrInvalidParam = errors.New("invalid url parameter")
View Source
var MaxMultipartMemory int64 = 32 << 20

Maximum memory in bytes for file uploads

View Source
var ModeProduction bool

Debug /or production, defaults to false. If in production, turns off ConsoleWriter and writes to the io.Writer provide to the router.

View Source
var StrictSlash bool = false

Enable Strict Trailing slash per URL

View Source
var ValidationTag string = "validate"

Validation tag, default "validate"

Functions

func ForEach added in v0.1.3

func ForEach[T any](arr []T, f func(val T))

Loop through any slice or array.

func IsValidEmail

func IsValidEmail(email string) bool

This pattern uses a combination of character sets, character ranges, and optional groups to match the structure of an email address. It should match most valid email addresses, including ones with multiple dots in the domain name and ones with internationalized domain names (IDNs).

func MapSlice added in v0.1.3

func MapSlice[T any, V any](arr []T, f func(val T) V) []V

Same transorm slice. First generic param is array type. Second param is the type of the return slice element type.

func WriteToTempFile

func WriteToTempFile(name string, data []byte) (filename string, rmDir func(), err error)

Write data to a temporary file with given name. Returns absolute path to the file written to, function to delete the teporary directory where this file was created and an error if any. Temporary file created with permissions 0754.

Types

type Context

type Context struct {
	Request  *http.Request     // Incoming request
	Response *Writer           // http response writer
	Params   map[string]string // Path parameters

	// Logger
	Logger zerolog.Logger
	// contains filtered or unexported fields
}

Context encapsulates request/response operations.

func (*Context) Abort

func (c *Context) Abort(status int, message string)

Abort the request and cancel all processing down the middleware chain. Sends a response with the given status code and message.

func (*Context) AbortRequest added in v0.1.4

func (c *Context) AbortRequest()

Marks the request as aborted without sending any response. All pending middleware will not run.

func (*Context) AbortWithError

func (c *Context) AbortWithError(status int, err error)

Abort the request and cancel all processing down the middleware chain. Sends a response with the given status code and message.

func (*Context) BearerToken

func (c *Context) BearerToken() string

Extract Bearer Token from Authorization header. If the token is not in the correct format: Bearer xxxxxxx, returns an empty string.

func (*Context) Binary

func (c *Context) Binary(data []byte)

Send binary data as response. Sets appropriate content-type as application/octet-stream.

func (*Context) BindJSON

func (c *Context) BindJSON(v any) error

Bind the request body to a struct.

func (*Context) BindXML

func (c *Context) BindXML(v any) error

func (*Context) File

func (c *Context) File(filePath string)

Send a file at filePath as a binary response with http.ServeFile

func (*Context) Get

func (c *Context) Get(key string) (value any, ok bool)

Get value from the context. Goroutine safe.

func (*Context) HTML

func (c *Context) HTML(html string)

Send an HTML response as text/html.

func (*Context) Header added in v0.0.4

func (c *Context) Header(key string, value string)

func (*Context) IntParam

func (c *Context) IntParam(key string) (int, error)

Get parameter as an integer. If key does not exist not a valid integer, sends a 401 http response.

func (*Context) IntQuery

func (c *Context) IntQuery(key string) (int, error)

Get parameter as an integer. If key does not exist not a valid integer, IntParam panics.

func (*Context) JSON

func (c *Context) JSON(data any)

Send encoded JSON response. Sets conent-type header as application/json.

func (*Context) MustBindJSON

func (c *Context) MustBindJSON(v any) validator.ValidationErrors

Alias to c.BindJSON followed by c.Validate. Panics if BindJSON on v fails.

func (*Context) MustBindXML

func (c *Context) MustBindXML(v any) validator.ValidationErrors

Alias to c.BindXML followed by c.Validate. Panics if BindXML on v fails. v should be a pointer to struct, slice or array.

func (*Context) MustGet

func (c *Context) MustGet(key string) (value any)

Get value from the context or panic if value not in context. Goroutine safe.

func (*Context) Param added in v0.1.4

func (c *Context) Param(key string) string

returns a parameter for the key. if it does not exist, returns an empty string.

func (*Context) ParseMultipartFile

func (c *Context) ParseMultipartFile(fieldName string) (*multipart.FileHeader, error)

Parse a single file from the request body. If no file exists for the field name, returns an error.

func (*Context) ParseMultipartForm

func (c *Context) ParseMultipartForm() (map[string][]string, map[string][]*multipart.FileHeader, error)

This function returns two maps: one for the form values, and one for the files. The files map is a map of string slices of *multipart.FileHeader values, representing the uploaded files.

Max Memory used is 32 << 20.

func (*Context) Query

func (c *Context) Query(key string) string

Returns a query parameter by key.

func (*Context) Read

func (c *Context) Read(p []byte) (int, error)

Read the request body into buffer p. Makes Context a Reader interface.

func (*Context) Redirect

func (c *Context) Redirect(url string)

Redirect the client to a different URL. Sets redirect code to http.StatusMovedPermanently.

func (*Context) Render

func (c *Context) Render(status int, data any, filenames ...string)

Render a template/templates using template.ParseFiles using data and sends the resulting output as a text/html response.

func (*Context) SaveMultipartFile

func (c *Context) SaveMultipartFile(file *multipart.FileHeader, destDir string) (string, error)

Save the multipart file to disk using a random name into destDir directory. Returns the path to the destination filename and error if any.

func (*Context) SaveMultipartFiles

func (c *Context) SaveMultipartFiles(formFiles map[string][]*multipart.FileHeader,
	destDir string) (filnames []string, err error)

Save multiple multipart files to disk. Returns filenames of the saved files and an error if any of the os/io operations fail.

func (*Context) Set

func (c *Context) Set(key string, value any)

Set value onto the context. Goroutine safe.

func (*Context) Status

func (c *Context) Status(statusCode int) *Context

Write the status code of the response. Chainable.

func (*Context) StatusCode added in v0.0.3

func (c *Context) StatusCode() int

func (*Context) String added in v0.0.3

func (c *Context) String(text string)

Send a text response as text/plain.

func (*Context) UintParam

func (c *Context) UintParam(key string) (uint, error)

Get parameter as an integer. If key does not exist not a valid integer, IntParam panics.

func (*Context) UintQuery

func (c *Context) UintQuery(key string) (uint, error)

Get parameter as an integer. If key does not exist not a valid integer, IntParam panics.

func (*Context) Validate

func (c *Context) Validate(v any) validator.ValidationErrors

Validates structs, pointers to structs and slices/arrays of structs. Validate will panic if obj is not struct, slice, array or pointers to the same.

func (*Context) ValidationError

func (c *Context) ValidationError(err validator.ValidationErrors)

Sends translated error messages from go-playground validator using en local as JSON.

func (*Context) Write

func (c *Context) Write(data []byte) (int, error)

Write the data into the response. Makes Context a Writer interface.

type CorsConfig added in v0.0.4

type CorsConfig struct {

	/*
		The Access-Control-Allow-Origin response header indicates whether the response can be
		shared with requesting code from the given origin.

		Passing in []string{"*"} will allow all origins
	*/
	AllowedOrigins []string

	/*
		The Access-Control-Allow-Methods response header specifies one or more methods allowed
		when accessing a resource in response to a preflight request
	*/
	AllowedMethods []string

	/*
		The Access-Control-Allow-Headers response header is used in response to a preflight request
		which includes the Access-Control-Request-Headers to indicate which HTTP headers can be used
		 during the actual request
	*/
	AllowedHeaders []string

	/*
		The Access-Control-Expose-Headers response header allows a server to indicate which response headers should be made available to scripts running in the browser, in response to a cross-origin request
	*/
	ExposeHeaders []string

	/*
		The Access-Control-Allow-Credentials response header tells browsers whether to expose the response to the frontend JavaScript code when the request's credentials mode (Request.credentials) is include
	*/
	AllowCredentials bool

	/*
		The Access-Control-Max-Age response header indicates how long the results of a preflight request (that is the information contained in the Access-Control-Allow-Methods and Access-Control-Allow-Headers headers) can be cached.
	*/
	MaxAge time.Duration
}

CorsConfig is the configuration struct that sets up the cors middleware. All values are passed to the Headers as provided without special defaults.

type HandlerFunc

type HandlerFunc func(c *Context)

func Logger added in v0.0.3

func Logger(next HandlerFunc) HandlerFunc

A simple logging middleware. Logs the Request Method, Path, IP, Browser, Latency.

func Recovery added in v0.0.3

func Recovery(next HandlerFunc) HandlerFunc

Custom server recovery middleware.

func WrapH added in v0.0.3

func WrapH(h http.Handler) HandlerFunc

Wraps a standard http.Handler.

func WrapHF added in v0.0.3

func WrapHF(h http.HandlerFunc) HandlerFunc

Wraps a standard http.HandlerFunc.

type Map added in v0.0.3

type Map map[string]any

type MiddlewareFunc

type MiddlewareFunc func(next HandlerFunc) HandlerFunc

func Cors added in v0.0.4

func Cors(m CorsConfig) MiddlewareFunc

Cors middleware. m CorsConfig configures the CORS response headers.

type Router

type Router struct {

	// Request logger
	Logger zerolog.Logger
	// contains filtered or unexported fields
}

Base Router implements the http.Handler interface.

func Default

func Default(out ...io.Writer) *Router

Initializes an instance of gora.Router. Returns a pointer to a new router with the logging and recovery middleware applied. If you don't want whese middleware, call New() instead and specify middleware yourself. out is where to the logger should write. Defaults to os.Stderr

func New

func New(out ...io.Writer) *Router

Returns a pointer to a new router. If you want logging middleware and recovery middleware applied, use Default() instead. out is where to the logger should write. Defaults to os.Stderr

func (*Router) CONNECT

func (r *Router) CONNECT(pattern string, handler HandlerFunc, middleware ...MiddlewareFunc)

func (*Router) DELETE

func (r *Router) DELETE(pattern string, handler HandlerFunc, middleware ...MiddlewareFunc)

func (*Router) GET

func (r *Router) GET(pattern string, handler HandlerFunc, middleware ...MiddlewareFunc)

func (*Router) Group

func (r *Router) Group(prefix string, middleware ...MiddlewareFunc) *RouterGroup

Create a new router group.

func (*Router) HEAD

func (r *Router) HEAD(pattern string, handler HandlerFunc, middleware ...MiddlewareFunc)

func (*Router) NotFound

func (r *Router) NotFound(handler HandlerFunc, middleware ...MiddlewareFunc)

Connect a handler to be called if no pattern matches the request path.

func (*Router) OPTIONS

func (r *Router) OPTIONS(pattern string, handler HandlerFunc, middleware ...MiddlewareFunc)

func (*Router) PATCH

func (r *Router) PATCH(pattern string, handler HandlerFunc, middleware ...MiddlewareFunc)

func (*Router) POST

func (r *Router) POST(pattern string, handler HandlerFunc, middleware ...MiddlewareFunc)

func (*Router) PUT

func (r *Router) PUT(pattern string, handler HandlerFunc, middleware ...MiddlewareFunc)

func (*Router) Routes

func (r *Router) Routes() []route

func (*Router) Run

func (r *Router) Run(addr string)

func (*Router) RunTLS

func (r *Router) RunTLS(addr string, certFile, keyFile string)

func (*Router) ServeHTTP

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

Serves the http request. Implements the http.Handler interface.

func (*Router) Static

func (r *Router) Static(root, dirname, stripPrefix string)

Serve static files with the http.FileServer If root is not "/", you may want to provide a stripPrefix string to tidy up the request path. e.g

r := gora.Default()
r.Static("/static", ".", "/static")

func (*Router) StaticEmbedFS

func (r *Router) StaticEmbedFS(staticEmbed StaticEmbed)

Serve files in an embedded directory. This is essential to embed build directories from frontend frameworks like svelte-kit, react, astro etc. Serves index.html at the root of the file system as if it was mounted at root. If ignore slice is not nil or empty, request path matching these routes are skipped.

func (*Router) TRACE

func (r *Router) TRACE(pattern string, handler HandlerFunc, middleware ...MiddlewareFunc)

func (*Router) Use

func (r *Router) Use(middleware ...MiddlewareFunc)

Apply middleware to the router.

type RouterGroup

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

Router group allows for nesting of url routes. Has similar methods as the base router.

func (*RouterGroup) CONNECT

func (g *RouterGroup) CONNECT(pattern string, handler HandlerFunc, middleware ...MiddlewareFunc)

func (*RouterGroup) DELETE

func (g *RouterGroup) DELETE(pattern string, handler HandlerFunc, middleware ...MiddlewareFunc)

func (*RouterGroup) GET

func (g *RouterGroup) GET(pattern string, handler HandlerFunc, middleware ...MiddlewareFunc)

func (*RouterGroup) Group added in v0.1.4

func (g *RouterGroup) Group(prefix string, middleware ...MiddlewareFunc) *RouterGroup

Create a new router group on a router group.

func (*RouterGroup) HEAD

func (g *RouterGroup) HEAD(pattern string, handler HandlerFunc, middleware ...MiddlewareFunc)

func (*RouterGroup) OPTIONS

func (g *RouterGroup) OPTIONS(pattern string, handler HandlerFunc, middleware ...MiddlewareFunc)

Other methods

func (*RouterGroup) PATCH

func (g *RouterGroup) PATCH(pattern string, handler HandlerFunc, middleware ...MiddlewareFunc)

func (*RouterGroup) POST

func (g *RouterGroup) POST(pattern string, handler HandlerFunc, middleware ...MiddlewareFunc)

func (*RouterGroup) PUT

func (g *RouterGroup) PUT(pattern string, handler HandlerFunc, middleware ...MiddlewareFunc)

func (*RouterGroup) Static added in v0.1.3

func (g *RouterGroup) Static(pattern, dirname, stripPrefix string)

func (*RouterGroup) TRACE

func (g *RouterGroup) TRACE(pattern string, handler HandlerFunc, middleware ...MiddlewareFunc)

func (*RouterGroup) Use

func (g *RouterGroup) Use(middleware ...MiddlewareFunc)

type StaticEmbed

type StaticEmbed struct {
	EmbedFS        *embed.FS // The embed build/dist directory
	Route          string    //Route to serve your frontend application from. Default: "/"
	Dirname        string    // directory prefix for your build directory. Default: "build"
	IgnorePatterns []string  // path patterns to ignore. e.g "/api", "/ws"
	IndexFile      string    // Path to index.html relative, defaults to "index.html"
}

Configuration struct for embedding an embedded build directory.

In SPAMode, a catch-all route hooked up to send every failed request back to index.html so that the client-side router can handle it.

type Validator

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

func NewValidator

func NewValidator(tagName string) *Validator

returns a new Validator for tagName Instantiate a new validator with universal translation based on the 'en' locale. See example at https://github.com/go-playground/validator/blob/master/_examples/translations/main.go

func (*Validator) SetTagName

func (val *Validator) SetTagName(tagName string)

func (*Validator) TranslateErrors

func (val *Validator) TranslateErrors(errs validator.ValidationErrors) validator.ValidationErrorsTranslations

func (*Validator) Validate

func (val *Validator) Validate(obj any) validator.ValidationErrors

Validates structs, pointers to structs and slices/arrays of structs Validate will panic if obj is not struct, slice, array or pointers to the same.

type Writer added in v0.0.3

type Writer struct {
	http.ResponseWriter
	// contains filtered or unexported fields
}

func (*Writer) WriteHeader added in v0.0.3

func (w *Writer) WriteHeader(statusCode int)

Implement WriteHeader to intercept the statusCode of the request for logging.

Jump to

Keyboard shortcuts

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