router

package
v0.0.0-...-3264219 Latest Latest
Warning

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

Go to latest
Published: Feb 22, 2025 License: MIT Imports: 17 Imported by: 0

Documentation

Index

Constants

View Source
const (
	ContentTypeJSON = "application/json"
	ContentTypeXML  = "application/xml"
	ContentTypeHTML = "text/html"
)

Content negotiation

Variables

This section is empty.

Functions

func ContentNegotiationHandler

func ContentNegotiationHandler(w http.ResponseWriter, r *http.Request)

func NegotiateContentType

func NegotiateContentType(acceptHeader string) string

func PathPrefix

func PathPrefix(path string)

func SetAppInstance

func SetAppInstance(app *Router)

SetAppInstance sets the singleton App instance.

func WrapCustomHandler

func WrapCustomHandler(handler CustomHandler) http.HandlerFunc

WrapCustomHandler converts a CustomHandler to http.HandlerFunc.

Types

type CustomHandler

type CustomHandler func(ctx *context.Context)

CustomHandler is a function type that takes a custom Context.

func UnWrapCustomHandler

func UnWrapCustomHandler(handler http.HandlerFunc) CustomHandler

UnWrapCustomHandler converts a http.HandlerFunc to CustomHandler.

type HTTPError

type HTTPError struct {
	Code    int
	Message string
}

HTTPError represents an error with an associated HTTP status code.

func NewHTTPError

func NewHTTPError(code int, message string) *HTTPError

NewHTTPError creates a new HTTPError instance with the given status code and message.

Example usage:

err := NewHTTPError(http.StatusBadRequest, "Bad Request: missing parameters")

func (*HTTPError) Error

func (e *HTTPError) Error() string

Error returns a string representation of the HTTPError.

type HTTPMethod

type HTTPMethod string

HTTPMethod represents an HTTP method as a custom type.

const (
	GET     HTTPMethod = "GET"
	POST    HTTPMethod = "POST"
	PUT     HTTPMethod = "PUT"
	DELETE  HTTPMethod = "DELETE"
	OPTIONS HTTPMethod = "OPTIONS"
	HEAD    HTTPMethod = "HEAD"
	PATCH   HTTPMethod = "PATCH"
)

Define constants for each HTTP method.

type Option

type Option func(*Router)

Option is a function that configures a Router.

func WithCORS

func WithCORS(options middleware.CORSOptions) Option

WithCORS enables CORS middleware with specific options. This option configures the CORS settings for the router.

Example usage:

r := router.NewRouter(router.WithCORS(middleware.CORSOptions{...}))

func WithCaching

func WithCaching(client *redis.Client, ttl time.Duration, cacheControl bool) Option

WithCaching is an option function that enables caching for the router using Redis.

This function returns an Option that can be passed to the Router to enable response caching with Redis. Cached responses will be stored in Redis with a specified Time-To-Live (TTL), meaning they will automatically expire after the specified duration.

Parameters:

  • redisAddr (string): The address of the Redis server, e.g., "localhost:6379".
  • ttl (time.Duration): The Time-To-Live for cached responses. Responses will be removed from the cache after this duration.

Returns:

  • Option: An option that applies caching middleware to the router.

Example usage:

router := NewRouter(
    WithCaching("localhost:6379", 5*time.Minute),
)

This will enable caching for the router, storing responses in Redis for 5 minutes.

Note: Ensure that the Redis server is running and accessible at the specified address.

func WithCookieParser

func WithCookieParser() Option

WithCookieParser enables cookie parsing middleware. This option ensures that cookies are parsed and available in the request context.

Example usage:

r := router.NewRouter(router.WithCookieParser())

func WithCsrf

func WithCsrf() Option

WithCsrf is an option function that enables CSRF protection for the router.

This function returns an Option that can be passed to the Router to enable Cross-Site Request Forgery (CSRF) protection using a middleware. The middleware generates and validates CSRF tokens to protect against malicious cross-origin requests, ensuring that requests are coming from legitimate users.

Returns:

  • Option: An option that applies CSRF protection middleware to the router.

Example usage:

router := NewRouter(
    WithCsrf(),
)

This will enable CSRF protection for all routes in the router.

func WithFileUpload

func WithFileUpload(uploadDir string, maxFileSize int64, allowedExts []string) Option

WithFileUpload enables file upload middleware with the specified upload directory. This option configures the router to handle file uploads and save them to the given directory.

Example usage:

r := router.NewRouter(router.WithFileUpload("/uploads"))

func WithInMemoryRateLimiter

func WithInMemoryRateLimiter(NumShards int, Limit int, Interval time.Duration, CleanupInterval time.Duration) Option

WithRateLimiter enables rate limiting middleware with the specified limit and interval. This option configures the rate limiter for the router.

Example usage:

r := router.NewRouter(router.WithRateLimiter(100, time.Minute))

func WithJSONParser

func WithJSONParser(options middleware.ParserOptions) Option

WithJSONParser enables JSON parsing middleware for request bodies. This option ensures that incoming JSON payloads are parsed and available in the request context.

Example usage:

r := router.NewRouter(router.WithJSONParser())

func WithRedisRateLimiter

func WithRedisRateLimiter(client *redis.Client, limit int, interval time.Duration) Option

WithRateLimiter enables rate limiting middleware with the specified limit and interval. This option configures the rate limiter for the router.

Example usage:

r := router.NewRouter(router.WithRateLimiter(100, time.Minute))

func WithTemplateRendering

func WithTemplateRendering(templateDir string) Option

WithTemplateRendering sets up the router to use the TemplateMiddleware for rendering HTML templates. It automatically loads all `.html` files from the specified directory and makes them available for rendering within the application's handlers.

The middleware parses all `.html` files from the provided directory during initialization and injects the parsed templates into the request context, allowing handlers to access and render the templates as needed.

Usage:

router := NewRouter(
    WithTemplateRendering("templates"), // Directory containing all .html files
)

router.HandleFunc("/", yourHandler)

In the handler, you can retrieve and execute a template:

func yourHandler(w http.ResponseWriter, r *http.Request) {
    tmpl := middleware.GetTemplate(r.Context())
    tmpl.ExecuteTemplate(w, "index.html", nil) // Renders the index.html template
}

Parameters:

  • templateDir: The directory containing the `.html` files to be used as templates.

Returns:

  • Option: A function that configures the router to use the template rendering middleware.

func WithXss

func WithXss() Option

WithXss is an option function that enables XSS protection for the router.

This function returns an Option that can be passed to the Router to enable Cross-Site Scripting (XSS) protection using a middleware. The middleware helps to sanitize and filter out malicious scripts from user input, thereby preventing XSS attacks.

Returns:

  • Option: An option that applies XSS protection middleware to the router.

Example usage:

router := NewRouter(
    WithXss(),
)

This will enable XSS protection for all routes in the router, ensuring that user input is sanitized and secure.

type RateLimiterType

type RateLimiterType = middleware.RateLimiterType
const (
	InMemory RateLimiterType = iota
	RedisBacked
)

type Router

type Router struct {
	Mux *mux.Router
	// contains filtered or unexported fields
}

Router represents an HTTP router with middleware support and error handling.

func GetApp

func GetApp() *Router

GetAppInstance returns the singleton App instance.

func NewRouter

func NewRouter(options ...Option) *Router

NewRouter creates a new Router with optional configuration. You can pass options like WithCORS or WithJSONParser to configure the router.

Example usage:

r := router.NewRouter(
	router.WithCORS(middleware.CORSOptions{}),
	router.WithJSONParser(),
)

func (*Router) AddRoute

func (r *Router) AddRoute(path string, handler CustomHandler)

AddRoute adds a route with the given path and handler function. This method applies context, error handling, and logging to the handler.

Example usage:

r.AddRoute("/ping", func(ctx *context.Context) {
	ctx.JSON(http.StatusOK, map[string]string{"message": "pong"})
})

func (*Router) Delete

func (r *Router) Delete(path string, handler CustomHandler) *Router

Delete registers a handler for DELETE requests.

func (*Router) Get

func (r *Router) Get(path string, handler CustomHandler) *Router

Get registers a handler for GET requests.

func (*Router) Listen

func (r *Router) Listen(addr string, httpConfig *config.HttpConfig) error

Start http server

func (*Router) Patch

func (r *Router) Patch(path string, handler CustomHandler) *Router

Patch registers a handler for PATCH requests.

func (*Router) Post

func (r *Router) Post(path string, handler CustomHandler) *Router

Post registers a handler for POST requests.

func (*Router) Put

func (r *Router) Put(path string, handler CustomHandler) *Router

Put registers a handler for PUT requests.

func (*Router) ServeStatic

func (r *Router) ServeStatic(pathPrefix, dir string)

ServeStatic creates a file server handler to serve static files from the given directory. The pathPrefix is stripped from the request URL before serving the file.

Example usage:

 r := LessGo.NewRouter(
		LessGo.WithCORS(*corsOptions),
		LessGo.WithRateLimiter(100, 1*time.Minute),
		LessGo.WithJSONParser(),
		LessGo.WithCookieParser(),
	)
r.ServeStatic("/static/", "/path/to/static/files"))

func (*Router) Start

func (r *Router) Start(addr string, httpConfig *config.HttpConfig) error

Start starts the HTTP server on the specified address. It applies all middleware and listens for incoming requests.

Example usage:

err := r.Start(":8080")
if err != nil {
	log.Fatalf("Server failed: %v", err)
}

func (*Router) SubRouter

func (r *Router) SubRouter(pathPrefix string, options ...Option) *Router

SubRouter creates a subrouter with the given path prefix.

Example usage:

subRouter := r.SubRouter("/api")
subRouter.AddRoute("/ping", handler)

func (*Router) Swagger

func (r *Router) Swagger(path string, handler http.HandlerFunc)

Server Swagger

func (*Router) Use

func (r *Router) Use(m middleware.Middleware)

Use adds a middleware to the router's middleware stack.

Example usage:

r.Use(middleware.LoggingMiddleware{})

func (*Router) WithContentNegotiation

func (r *Router) WithContentNegotiation(next http.HandlerFunc) http.HandlerFunc

Jump to

Keyboard shortcuts

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