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 ¶
- Variables
- func ForEach[T any](arr []T, f func(val T))
- func IsValidEmail(email string) bool
- func MapSlice[T any, V any](arr []T, f func(val T) V) []V
- func WriteToTempFile(name string, data []byte) (filename string, rmDir func(), err error)
- type Context
- func (c *Context) Abort(status int, message string)
- func (c *Context) AbortRequest()
- func (c *Context) AbortWithError(status int, err error)
- func (c *Context) BearerToken() string
- func (c *Context) Binary(data []byte)
- func (c *Context) BindJSON(v any) error
- func (c *Context) BindXML(v any) error
- func (c *Context) File(filePath string)
- func (c *Context) Get(key string) (value any, ok bool)
- func (c *Context) HTML(html string)
- func (c *Context) Header(key string, value string)
- func (c *Context) IntParam(key string) (int, error)
- func (c *Context) IntQuery(key string) (int, error)
- func (c *Context) JSON(data any)
- func (c *Context) MustBindJSON(v any) validator.ValidationErrors
- func (c *Context) MustBindXML(v any) validator.ValidationErrors
- func (c *Context) MustGet(key string) (value any)
- func (c *Context) Param(key string) string
- func (c *Context) ParseMultipartFile(fieldName string) (*multipart.FileHeader, error)
- func (c *Context) ParseMultipartForm() (map[string][]string, map[string][]*multipart.FileHeader, error)
- func (c *Context) Query(key string) string
- func (c *Context) Read(p []byte) (int, error)
- func (c *Context) Redirect(url string)
- func (c *Context) Render(status int, data any, filenames ...string)
- func (c *Context) SaveMultipartFile(file *multipart.FileHeader, destDir string) (string, error)
- func (c *Context) SaveMultipartFiles(formFiles map[string][]*multipart.FileHeader, destDir string) (filnames []string, err error)
- func (c *Context) Set(key string, value any)
- func (c *Context) Status(statusCode int) *Context
- func (c *Context) StatusCode() int
- func (c *Context) String(text string)
- func (c *Context) UintParam(key string) (uint, error)
- func (c *Context) UintQuery(key string) (uint, error)
- func (c *Context) Validate(v any) validator.ValidationErrors
- func (c *Context) ValidationError(err validator.ValidationErrors)
- func (c *Context) Write(data []byte) (int, error)
- type CorsConfig
- type HandlerFunc
- type Map
- type MiddlewareFunc
- type Router
- func (r *Router) CONNECT(pattern string, handler HandlerFunc, middleware ...MiddlewareFunc)
- func (r *Router) DELETE(pattern string, handler HandlerFunc, middleware ...MiddlewareFunc)
- func (r *Router) GET(pattern string, handler HandlerFunc, middleware ...MiddlewareFunc)
- func (r *Router) Group(prefix string, middleware ...MiddlewareFunc) *RouterGroup
- func (r *Router) HEAD(pattern string, handler HandlerFunc, middleware ...MiddlewareFunc)
- func (r *Router) NotFound(handler HandlerFunc, middleware ...MiddlewareFunc)
- func (r *Router) OPTIONS(pattern string, handler HandlerFunc, middleware ...MiddlewareFunc)
- func (r *Router) PATCH(pattern string, handler HandlerFunc, middleware ...MiddlewareFunc)
- func (r *Router) POST(pattern string, handler HandlerFunc, middleware ...MiddlewareFunc)
- func (r *Router) PUT(pattern string, handler HandlerFunc, middleware ...MiddlewareFunc)
- func (r *Router) Routes() []route
- func (r *Router) Run(addr string)
- func (r *Router) RunTLS(addr string, certFile, keyFile string)
- func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request)
- func (r *Router) Static(root, dirname, stripPrefix string)
- func (r *Router) StaticEmbedFS(staticEmbed StaticEmbed)
- func (r *Router) TRACE(pattern string, handler HandlerFunc, middleware ...MiddlewareFunc)
- func (r *Router) Use(middleware ...MiddlewareFunc)
- type RouterGroup
- func (g *RouterGroup) CONNECT(pattern string, handler HandlerFunc, middleware ...MiddlewareFunc)
- func (g *RouterGroup) DELETE(pattern string, handler HandlerFunc, middleware ...MiddlewareFunc)
- func (g *RouterGroup) GET(pattern string, handler HandlerFunc, middleware ...MiddlewareFunc)
- func (g *RouterGroup) Group(prefix string, middleware ...MiddlewareFunc) *RouterGroup
- func (g *RouterGroup) HEAD(pattern string, handler HandlerFunc, middleware ...MiddlewareFunc)
- func (g *RouterGroup) OPTIONS(pattern string, handler HandlerFunc, middleware ...MiddlewareFunc)
- func (g *RouterGroup) PATCH(pattern string, handler HandlerFunc, middleware ...MiddlewareFunc)
- func (g *RouterGroup) POST(pattern string, handler HandlerFunc, middleware ...MiddlewareFunc)
- func (g *RouterGroup) PUT(pattern string, handler HandlerFunc, middleware ...MiddlewareFunc)
- func (g *RouterGroup) Static(pattern, dirname, stripPrefix string)
- func (g *RouterGroup) TRACE(pattern string, handler HandlerFunc, middleware ...MiddlewareFunc)
- func (g *RouterGroup) Use(middleware ...MiddlewareFunc)
- type StaticEmbed
- type Validator
- type Writer
Constants ¶
This section is empty.
Variables ¶
var (
ErrEmptyRequestBody = errors.New("empty request body")
)
var ErrInvalidParam = errors.New("invalid url parameter")
var MaxMultipartMemory int64 = 32 << 20
Maximum memory in bytes for file uploads
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.
var StrictSlash bool = false
Enable Strict Trailing slash per URL
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 ¶
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
Same transorm slice. First generic param is array type. Second param is the type of the return slice element type.
func WriteToTempFile ¶
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 ¶
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 ¶
Abort the request and cancel all processing down the middleware chain. Sends a response with the given status code and message.
func (*Context) BearerToken ¶
Extract Bearer Token from Authorization header. If the token is not in the correct format: Bearer xxxxxxx, returns an empty string.
func (*Context) Binary ¶
Send binary data as response. Sets appropriate content-type as application/octet-stream.
func (*Context) IntParam ¶
Get parameter as an integer. If key does not exist not a valid integer, sends a 401 http response.
func (*Context) IntQuery ¶
Get parameter as an integer. If key does not exist not a valid integer, IntParam panics.
func (*Context) MustBindJSON ¶
Alias to c.BindJSON followed by c.Validate. Panics if BindJSON on v fails.
func (*Context) MustBindXML ¶
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 ¶
Get value from the context or panic if value not in context. Goroutine safe.
func (*Context) Param ¶ added in v0.1.4
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) Redirect ¶
Redirect the client to a different URL. Sets redirect code to http.StatusMovedPermanently.
func (*Context) Render ¶
Render a template/templates using template.ParseFiles using data and sends the resulting output as a text/html response.
func (*Context) SaveMultipartFile ¶
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) StatusCode ¶ added in v0.0.3
func (*Context) UintParam ¶
Get parameter as an integer. If key does not exist not a valid integer, IntParam panics.
func (*Context) UintQuery ¶
Get parameter as an integer. If key does not exist not a valid integer, IntParam panics.
func (*Context) Validate ¶
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.
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 WrapHF ¶ added in v0.0.3
func WrapHF(h http.HandlerFunc) HandlerFunc
Wraps a standard http.HandlerFunc.
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 ¶
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 ¶
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) ServeHTTP ¶
func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request)
Serves the http request. Implements the http.Handler interface.
func (*Router) Static ¶
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 ¶
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 (*Validator) TranslateErrors ¶
func (val *Validator) TranslateErrors(errs validator.ValidationErrors) validator.ValidationErrorsTranslations
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
Implement WriteHeader to intercept the statusCode of the request for logging.