egor

package
v0.2.5 Latest Latest
Warning

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

Go to latest
Published: Mar 23, 2024 License: MIT Imports: 25 Imported by: 0

Documentation

Overview

Package egor(enhanced go router) is a minimalistic, robust http router based on the go 1.22 enhanced routing capabilities. It adds a few features like middleware support, helper methods for defining routes, template rendering with automatic template inheritance(of a layout template), json,xml,form parsing based on content type, Single page application routing, grouping routes and more.

Has customizable built-in middleware for logging using the slog package, recovery, etag, cors and jwt middlewares. More middlewares can be added by implementing the Middleware type, a standard function that wraps an http.Handler.

No external libraries are included in the main package. The only external library is the middleware package which is optional.

Index

Constants

View Source
const (
	ContentTypeJSON          string = "application/json"
	ContentTypeXML           string = "application/xml"
	ContentTypeXForm         string = "application/x-www-form-urlencoded"
	ContentTypeMultipartForm string = "multipart/form-data"
	ContentTypeHTML          string = "text/html"
	ContentTypeCSV           string = "text/csv"
	ContentTypeText          string = "text/plain"
	ContentTypeEventStream   string = "text/event-stream"
)

Variables

View Source
var (
	// Match only the root path with "/" contrary to the default behavior which matches everything.
	// The default is true.
	StrictHome = true

	// Remove trailing slashes from the pattern (and req.URL.Path) except for the root path.
	// This means that if you register "/test/" and a request is made to "/test" or "/test/", it will not match.
	// The default is true.
	NoTrailingSlash = true
)

Functions

func BodyParser

func BodyParser(req *http.Request, v interface{}) error

BodyParser parses the request body and stores the result in v. v must be a pointer to a struct. Supported content types: application/json, application/x-www-form-urlencoded, multipart/form-data, application/xml For more robust form decoding we recommend using https://github.com/gorilla/schema package. Any form value can implement the FormScanner interface to implement custom form scanning. Struct tags are used to specify the form field name. If parsing forms, the default tag name is "form", followed by the "json" tag name, and then snake case of the field name.

func ExecuteTemplate added in v0.2.1

func ExecuteTemplate(w io.Writer, req *http.Request, name string, data Map) error

Execute a standalone template without a layout.

func FormData

func FormData(req *http.Request) url.Values

func FormFile

func FormFile(req *http.Request, key string) (*multipart.FileHeader, error)

FormFile returns the first file from the multipart form with the given key.

func FormFiles

func FormFiles(req *http.Request, key string) ([]*multipart.FileHeader, error)

FormFiles returns the files from the multipart form with the given key.

func FormValue

func FormValue(req *http.Request, key string) string

func GetContentType

func GetContentType(req *http.Request) string

func GetContextValue

func GetContextValue(req *http.Request, key any) interface{}

return a value from context.

func ParamInt

func ParamInt(req *http.Request, key string, defaults ...int) int

paramInt returns the value of the parameter as an integer

func ParseMultipartForm

func ParseMultipartForm(req *http.Request, maxMemory ...int64) (*multipart.Form, error)

ParseMultipartForm parses a request body as multipart form data.

func ParseTemplatesRecursive

func ParseTemplatesRecursive(rootDir string, funcMap template.FuncMap, suffix ...string) (*template.Template, error)

func ParseTemplatesRecursiveFS

func ParseTemplatesRecursiveFS(root fs.FS, rootDir string, funcMap template.FuncMap, suffix ...string) (*template.Template, error)

func Query

func Query(req *http.Request, key string, defaults ...string) string

func QueryInt

func QueryInt(req *http.Request, key string, defaults ...int) int

queryInt returns the value of the query as an integer

func QueryParser added in v0.0.5

func QueryParser(req *http.Request, v interface{}, tag ...string) error

QueryParser parses the query string and stores the result in v.

func Redirect

func Redirect(w http.ResponseWriter, req *http.Request, url string, status ...int)

Redirects the request to the given url. Default status code is 303 (http.StatusSeeOther)

func Render

func Render(w io.Writer, req *http.Request, name string, data Map)

Render a template of given name and pass the data to it. Make sure you are using egor.Router. Otherwise this function will panic. If a file extension is missing, it will be appended as ".html".

func SaveFile

func SaveFile(fh *multipart.FileHeader, dst string) error

save file

func SendError

func SendError(w http.ResponseWriter, req *http.Request, err error, status ...int)

Sends the error message to the client as html. If the Router has errorTemplate configured, the error template will be rendered instead. You can also pass a status code to be used. Yo do not need to call SendError after template rendering since the template will be rendered automatically if an error occurs during template rendering.

func SendFile

func SendFile(w http.ResponseWriter, req *http.Request, file string)

Wrapper around http.Servefile.

func SendHTML

func SendHTML(w http.ResponseWriter, html string) error

Send HTML string.

func SendJSON

func SendJSON(w http.ResponseWriter, v interface{}) error

Send v as JSON. Uses json.NewEncoder and sets content-type application/json for the response.

func SendJSONError

func SendJSONError(w http.ResponseWriter, resp map[string]any, status ...int)

sends the error message as a JSON string with the status code

func SendString

func SendString(w http.ResponseWriter, s string) error

Send string back to client.

func SetContextValue

func SetContextValue(req *http.Request, key any, value interface{})

Set a value in the request context. Also saves a copy in locals map. This allows for passing of passing of locals to templates.

func SnakeCase

func SnakeCase(s string) string

Types

type CTX

type CTX struct {
	Router *Router // The router
	// contains filtered or unexported fields
}

CTX is the custom context passed inside the request context. It carries a reference to the egor.Router and unexported fields for tracking locals.

It can be access from context with:

ctx := req.Context().Value(egor.ContextKey).(*egor.CTX)

func (*CTX) Get

func (r *CTX) Get(key any) any

func (*CTX) Set

func (r *CTX) Set(key any, value any)

type FormScanner

type FormScanner interface {
	// FormScan scans the form value and stores the result in the receiver.
	FormScan(value interface{}) error
}

FormScanner is an interface for types that can scan form values. It is used to implement custom form scanning for types that are not supported by default.

type Group

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

Group is a collection of routes with a common prefix.

func (*Group) Delete

func (g *Group) Delete(path string, handler http.HandlerFunc, middlewares ...Middleware)

DELETE request.

func (*Group) Get

func (g *Group) Get(path string, handler http.HandlerFunc, middlewares ...Middleware)

GET request.

func (*Group) Group

func (g *Group) Group(prefix string, middlewares ...Middleware) *Group

Creates a nested group with the given prefix and middleware.

func (*Group) Patch

func (g *Group) Patch(path string, handler http.HandlerFunc, middlewares ...Middleware)

PATCH request.

func (*Group) Post

func (g *Group) Post(path string, handler http.HandlerFunc, middlewares ...Middleware)

POST request.

func (*Group) Put

func (g *Group) Put(path string, handler http.HandlerFunc, middlewares ...Middleware)

PUT request.

func (*Group) Use

func (g *Group) Use(middlewares ...Middleware)

Use adds middlewares to the group.

type Map added in v0.1.7

type Map map[string]any

Generic type for any value used to pass data around between templates and context.

type Middleware

type Middleware func(next http.Handler) http.Handler

Standard function that wraps an http.Handler.

type ResponseWriter

type ResponseWriter struct {
	http.ResponseWriter // The embedded response writer.
	// contains filtered or unexported fields
}

func (*ResponseWriter) Flush

func (w *ResponseWriter) Flush()

Flush sends any buffered data to the client.

func (*ResponseWriter) Hijack

func (w *ResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error)

Hijack lets the caller take over the connection. After a call to Hijack the HTTP server library will not do anything else with the connection. see https://pkg.go.dev/net/http#Hijacker.Hijack

func (*ResponseWriter) Push

func (w *ResponseWriter) Push(target string, opts *http.PushOptions)

Push initiates an HTTP/2 server push. See https://pkg.go.dev/net/http#Pusher.Push

func (*ResponseWriter) Status

func (w *ResponseWriter) Status() int

Status returns the response status code.

func (*ResponseWriter) WriteHeader

func (w *ResponseWriter) WriteHeader(status int)

WriteHeader sends an HTTP response header with the provided status code.

type Router

type Router struct {

	// Handler for 404 not found errors. Note that when this is called,
	// The request parameters are not available, since they are populated by the http.ServeMux
	// when the request is matched to a route. So calling r.PathValue() will return "".
	NotFoundHandler http.Handler
	// contains filtered or unexported fields
}

Router is a simple router that implements the http.Handler interface

func NewRouter

func NewRouter(options ...RouterOption) *Router

NewRouter creates a new router with the given options. The router wraps the http.DefaultServeMux and adds routing and middleware capabilities.

func (*Router) Connect

func (r *Router) Connect(path string, handler http.HandlerFunc, middlewares ...Middleware)

CONNECT http request.

func (*Router) Delete

func (r *Router) Delete(path string, handler http.HandlerFunc, middlewares ...Middleware)

DELETE request.

func (*Router) ExecuteTemplate added in v0.2.1

func (r *Router) ExecuteTemplate(w io.Writer, name string, data Map) error

Execute a standalone template without a layout.

func (*Router) FaviconFS added in v0.0.2

func (r *Router) FaviconFS(fs http.FileSystem, path string)

Serve favicon.ico from the file system fs at path.

func (*Router) File

func (r *Router) File(path, file string)

Wrapper around http.ServeFile.

func (*Router) FileFS added in v0.0.2

func (r *Router) FileFS(fs http.FileSystem, prefix, path string)

func (*Router) Get

func (r *Router) Get(path string, handler http.HandlerFunc, middlewares ...Middleware)

GET request.

func (*Router) GetRegisteredRoutes

func (r *Router) GetRegisteredRoutes() []routeInfo

func (*Router) Group

func (r *Router) Group(prefix string, middlewares ...Middleware) *Group

Group creates a new group with the given prefix and options.

func (*Router) Head

func (r *Router) Head(path string, handler http.HandlerFunc, middlewares ...Middleware)

HEAD request.

func (*Router) Options

func (r *Router) Options(path string, handler http.HandlerFunc, middlewares ...Middleware)

OPTIONS. This may not be necessary as registering GET request automatically registers OPTIONS.

func (*Router) Patch

func (r *Router) Patch(path string, handler http.HandlerFunc, middlewares ...Middleware)

PATCH request.

func (*Router) Post

func (r *Router) Post(path string, handler http.HandlerFunc, middlewares ...Middleware)

POST request.

func (*Router) Put

func (r *Router) Put(path string, handler http.HandlerFunc, middlewares ...Middleware)

PUT request.

func (*Router) Redirect

func (r *Router) Redirect(w http.ResponseWriter, req *http.Request, url string, status ...int)

func (*Router) RedirectRoute

func (r *Router) RedirectRoute(w http.ResponseWriter, req *http.Request, pathname string, status ...int)

func (*Router) Render

func (r *Router) Render(w io.Writer, req *http.Request, name string, data Map)

Render the template tmpl with the data. If no template is configured, Render will panic. data is a map such that it can be extended with the request context keys if passContextToViews is set to true. If a file extension is missing, it will be appended as ".html".

func (*Router) RenderError added in v0.1.7

func (r *Router) RenderError(w http.ResponseWriter, err error, status ...int)

func (*Router) SPAHandler

func (r *Router) SPAHandler(frontendFS fs.FS, path string, buildPath string, options ...SPAOptions)

Serves Single Page applications like svelte-kit, react etc. frontendFS is any interface that satisfies fs.FS, like embed.FS, http.Dir() wrapping a directory etc. path is the mount point: likely "/". buildPath is the path to build output containing your entry point html file. The default entrypoint is "index.html" i.e buildPath/index.html. You can change the entrypoint with options. Passed options override all defaults.

func (*Router) ServeHTTP

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

Implementation for http.Handler.

func (*Router) Static

func (r *Router) Static(prefix, dir string)

Serve static assests at prefix in the directory dir. e.g r.Static("/static", "static"). This method will strip the prefix from the URL path.

func (*Router) StaticFS

func (r *Router) StaticFS(prefix string, fs http.FileSystem)

Like Static but for http.FileSystem. Use this to serve embedded assets with go/embed.

func (*Router) Trace

func (r *Router) Trace(path string, handler http.HandlerFunc, middlewares ...Middleware)

TRACE http request.

func (*Router) Use

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

Apply a global middleware to all routes.

type RouterOption

type RouterOption func(*Router)

Router option a function option for configuring the router.

func BaseLayout

func BaseLayout(baseLayout string) RouterOption

func ContentBlock

func ContentBlock(contentBlock string) RouterOption

func ErrorTemplate added in v0.1.7

func ErrorTemplate(errorTemplate string) RouterOption

ErrorTemplate sets the error template for the router. If set, this template will be used to render errors.

func PassContextToViews

func PassContextToViews(passContextToViews bool) RouterOption

func WithTemplates

func WithTemplates(t *template.Template) RouterOption

type SPAOptions

type SPAOptions struct {
	CacheControl     string           // default is empty, example: "public, max-age=31536000"
	ResponseModifier http.HandlerFunc // allows fo modifying request/response
	Skip             []string         // skip these routes and return 404 if they match
	Index            string           // default is index.html
}

SPAOptions for customizing the cache control and index file.

type Server

type Server struct {
	*http.Server
}

Wrapper around the standard http.Server. Adds easy graceful shutdown and functional options for customizing the server. This is the default server used by egor.

func NewServer

func NewServer(addr string, handler http.Handler, options ...ServerOption) *Server

Create a new Server instance.

func (*Server) GracefulShutdown

func (s *Server) GracefulShutdown(timeout ...time.Duration)

Gracefully shuts down the server. The default timeout is 5 seconds To wait for pending connections.

type ServerOption

type ServerOption func(*Server)

Option for configuring the server.

func WithIdleTimeout

func WithIdleTimeout(d time.Duration) ServerOption

func WithReadTimeout

func WithReadTimeout(d time.Duration) ServerOption

define a few options to configure the server

func WithTLSConfig

func WithTLSConfig(config *tls.Config) ServerOption

func WithWriteTimeout

func WithWriteTimeout(d time.Duration) ServerOption

Directories

Path Synopsis
middleware

Jump to

Keyboard shortcuts

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