lightning

package module
v0.11.0 Latest Latest
Warning

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

Go to latest
Published: Apr 15, 2026 License: MIT Imports: 19 Imported by: 10

README

Introduction

🚀🚀🚀 lightning is a lightweight and fast web framework for Go. It is designed to be easy to use and highly performant.

Go Reference GitHub

Features

  • Easy to use and quick to get started
  • Supports middleware
  • Fast routing, with routing algorithm implemented based on Trie tree
  • Support for grouping routes and applying middleware to specific groups
  • Customizable 404 Not Found and 500 Internal Server Error handler functions

Getting Started

To get started with lightning, simply install it using go get:

go get github.com/go-labx/lightning

Then, create a new lightning app and start adding routes:

package main

import (
	"github.com/go-labx/lightning"
	"net/http"
)

func main() {
	app := lightning.DefaultApp()

	app.Get("/ping", func(ctx *lightning.Context) {
		ctx.JSON(http.StatusOK, lightning.Map{
			"message": "pong",
		})
	})

	app.Run()
}

To run the lightning app, run the following command:

go run app.go

To verify that the server has started successfully, run the following command in your terminal:

curl http://127.0.0.1:6789/ping

Documentation

For more information on how to use lightning, check out the documentation.

Contributing

If you'd like to contribute to lightning, please see CONTRIBUTING.md for guidelines.

License

lightning is licensed under the MIT License.

Documentation

Index

Constants

View Source
const (
	MIMETextPlain                  = "text/plain"
	MIMETextHTML                   = "text/html"
	MIMEApplicationXML             = "application/xml"
	MIMEApplicationJSON            = "application/json"
	MIMEApplicationXMLCharsetUTF8  = "application/xml; charset=utf-8"
	MIMEApplicationJSONCharsetUTF8 = "application/json; charset=utf-8"
	MIMEMultipartForm              = "multipart/form-data"
	MIMEOctetStream                = "application/octet-stream"
)

MIME types

View Source
const (
	HeaderContentType        = "Content-Type"
	HeaderContentDisposition = "Content-Disposition"
	HeaderContentEncoding    = "Content-Encoding"
	HeaderContentLength      = "Content-Length"
	HeaderAccept             = "Accept"
	HeaderAcceptEncoding     = "Accept-Encoding"
	HeaderAcceptLanguage     = "Accept-Language"
	HeaderAuthorization      = "Authorization"
	HeaderCacheControl       = "Cache-Control"
	HeaderConnection         = "Connection"
	HeaderCookie             = "Cookie"
	HeaderHost               = "Host"
	HeaderOrigin             = "Origin"
	HeaderReferer            = "Referer"
	HeaderUserAgent          = "User-Agent"
	HeaderXRequestedWith     = "X-Requested-With"
	HeaderXRealIP            = "X-Real-IP"
	HeaderXForwardedFor      = "X-Forwarded-For"
	HeaderLocation           = "Location"
	HeaderUpgrade            = "Upgrade"
)

Header keys

View Source
const (
	StatusContinue                     = 100
	StatusSwitchingProtocols           = 101
	StatusOK                           = 200
	StatusCreated                      = 201
	StatusAccepted                     = 202
	StatusNoContent                    = 204
	StatusMultipleChoices              = 300
	StatusMovedPermanently             = 301
	StatusFound                        = 302
	StatusSeeOther                     = 303
	StatusNotModified                  = 304
	StatusUseProxy                     = 305
	StatusTemporaryRedirect            = 307
	StatusBadRequest                   = 400
	StatusUnauthorized                 = 401
	StatusPaymentRequired              = 402
	StatusForbidden                    = 403
	StatusNotFound                     = 404
	StatusMethodNotAllowed             = 405
	StatusNotAcceptable                = 406
	StatusProxyAuthRequired            = 407
	StatusRequestTimeout               = 408
	StatusConflict                     = 409
	StatusGone                         = 410
	StatusLengthRequired               = 411
	StatusPreconditionFailed           = 412
	StatusRequestEntityTooLarge        = 413
	StatusRequestURITooLarge           = 414
	StatusUnsupportedMediaType         = 415
	StatusRequestedRangeNotSatisfiable = 416
	StatusExpectationFailed            = 417
	StatusTeapot                       = 418
	StatusUpgradeRequired              = 426
	StatusInternalServerError          = 500
	StatusNotImplemented               = 501
	StatusBadGateway                   = 502
	StatusServiceUnavailable           = 503
	StatusGatewayTimeout               = 504
	StatusHTTPVersionNotSupported      = 505
)

HTTP status codes

View Source
const (
	MethodGet     = "GET"
	MethodHead    = "HEAD"
	MethodPost    = "POST"
	MethodPut     = "PUT"
	MethodPatch   = "PATCH"
	MethodDelete  = "DELETE"
	MethodConnect = "CONNECT"
	MethodOptions = "OPTIONS"
	MethodTrace   = "TRACE"
)

HTTP methods

Variables

This section is empty.

Functions

This section is empty.

Types

type Application

type Application struct {
	Config *Config

	Logger *lightlog.ConsoleLogger
	// contains filtered or unexported fields
}

Application is the main struct that holds the router, middlewares, and configuration.

func DefaultApp

func DefaultApp() *Application

DefaultApp returns a new instance of the Application struct with default middlewares

func NewApp

func NewApp(c ...*Config) *Application

NewApp returns a new instance of the Application struct.

func (*Application) AddRoute

func (app *Application) AddRoute(method string, pattern string, handlers []HandlerFunc)

AddRoute adds a new route to the router. It composes the global middlewares, route-specific middlewares, and the actual handler function to form a single MiddlewareFunc, and then adds it to the router.

func (*Application) Delete

func (app *Application) Delete(pattern string, handlers ...HandlerFunc)

Delete adds a new route with method "DELETE" to the router.

func (*Application) Get

func (app *Application) Get(pattern string, handlers ...HandlerFunc)

Get adds a new route with method "GET" to the router.

func (*Application) Group

func (app *Application) Group(prefix string) *Group

Group returns a new instance of the Group struct with the given prefix.

func (*Application) Head

func (app *Application) Head(pattern string, handlers ...HandlerFunc)

Head adds a new route with method "HEAD" to the router.

func (*Application) LoadHTMLGlob added in v0.5.0

func (app *Application) LoadHTMLGlob(pattern string)

LoadHTMLGlob loads HTML templates from a glob pattern and sets them in the Application struct. It uses the template.Must function to panic if there is an error parsing the templates. It also sets the funcMap in the Application struct to the funcMap passed in as an argument.

func (*Application) Options

func (app *Application) Options(pattern string, handlers ...HandlerFunc)

Options adds a new route with method "OPTIONS" to the router.

func (*Application) Patch

func (app *Application) Patch(pattern string, handlers ...HandlerFunc)

Patch adds a new route with method "PATCH" to the router.

func (*Application) Post

func (app *Application) Post(pattern string, handlers ...HandlerFunc)

Post adds a new route with method "POST" to the router.

func (*Application) Put

func (app *Application) Put(pattern string, handlers ...HandlerFunc)

Put adds a new route with method "PUT" to the router.

func (*Application) RequestHandler added in v0.9.0

func (app *Application) RequestHandler() fasthttp.RequestHandler

RequestHandler returns a fasthttp.RequestHandler for the Application.

func (*Application) Run

func (app *Application) Run(address ...string) error

Run starts the HTTP server and listens for incoming requests.

func (*Application) RunGraceful added in v0.8.0

func (app *Application) RunGraceful(shutdownTimeout int, address ...string) error

RunGraceful starts the HTTP server with graceful shutdown support. It listens for SIGINT and SIGTERM signals to trigger graceful shutdown. The shutdownTimeout specifies the maximum duration in seconds to wait for active connections to finish.

func (*Application) SetFuncMap added in v0.5.0

func (app *Application) SetFuncMap(funcMap template.FuncMap)

SetFuncMap sets the funcMap in the Application struct to the funcMap passed in as an argument.

func (*Application) Shutdown added in v0.8.0

func (app *Application) Shutdown()

Shutdown gracefully shuts down the server without interrupting active connections.

func (*Application) Static added in v0.5.0

func (app *Application) Static(root string, prefix string)

Static serves static files from the given root directory with the given prefix. If root is an absolute path, it is used directly. Otherwise, it is resolved relative to the executable's directory. If the file exists, it is served with a 200 status code. If the file does not exist, a 404 status code is returned with the text "Not Found". Accessing files outside the root directory is blocked to prevent path traversal attacks.

func (*Application) Use

func (app *Application) Use(middlewares ...Middleware)

Use adds one or more Middlewares to the array of middlewares in the Application struct.

type Config added in v0.4.0

type Config struct {
	AppName            string
	JSONEncoder        JSONMarshal
	JSONDecoder        JSONUnmarshal
	NotFoundHandler    HandlerFunc
	EnableDebug        bool
	DebugToken         string
	MaxRequestBodySize int64
	TrustedProxies     []string
}

Config holds the configuration for the Application.

type Context

type Context struct {
	App *Application

	Method string
	Path   string
	// contains filtered or unexported fields
}

Context represents the context of an HTTP request/response.

func NewContext added in v0.1.3

func NewContext(ctx *fasthttp.RequestCtx) *Context

NewContext creates a new Context object for the given fasthttp request context.

func (*Context) AcceptedLanguages added in v0.9.0

func (c *Context) AcceptedLanguages() []string

AcceptedLanguages returns the accepted languages from the request.

func (*Context) AddHeader

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

AddHeader adds a new header key-value pair to the response.

func (*Context) Body added in v0.1.5

func (c *Context) Body() []byte

Body returns the response body.

func (*Context) ContentType added in v0.9.0

func (c *Context) ContentType() string

ContentType returns the Content-Type header of the request.

func (*Context) Cookie

func (c *Context) Cookie(name string) string

Cookie returns the cookie value with the given name.

func (*Context) Cookies

func (c *Context) Cookies() map[string]string

Cookies returns all cookies from the request.

func (*Context) DelData

func (c *Context) DelData(key string)

DelData deletes a custom data field from the context.

func (*Context) DelHeader

func (c *Context) DelHeader(key string)

DelHeader deletes a given header from the response.

func (*Context) Fail

func (c *Context) Fail(code int, message string)

Fail writes a failed response with the given code and message.

func (*Context) File

func (c *Context) File(filepath string) error

File writes a file as the response. WARNING: The caller MUST validate that the path does not contain user-controlled input that could lead to directory traversal. Use FileFromSafeDir for safer file serving.

func (*Context) FileFromSafeDir added in v0.11.0

func (c *Context) FileFromSafeDir(safeDir string, requestPath string) error

FileFromSafeDir serves a file from the specified safe directory, preventing path traversal. It validates that the resolved file path stays within safeDir.

func (*Context) GetData

func (c *Context) GetData(key string) any

GetData returns the value of a custom data field for the context.

func (*Context) HTML added in v0.5.0

func (c *Context) HTML(code int, name string, data any)

HTML writes an HTML response with the given status code, template name, and data.

func (*Context) Header

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

Header returns the value of a given header.

func (*Context) Headers

func (c *Context) Headers() map[string]string

Headers returns all headers for the request.

func (*Context) IsAjax added in v0.9.0

func (c *Context) IsAjax() bool

IsAjax checks if the request is an AJAX request.

func (*Context) IsWebSocket added in v0.9.0

func (c *Context) IsWebSocket() bool

IsWebSocket checks if the request is a WebSocket upgrade request.

func (*Context) JSON

func (c *Context) JSON(code int, obj any)

JSON writes a JSON response with the given status code and object.

func (*Context) JSONBody

func (c *Context) JSONBody(v any, valid ...bool) error

JSONBody parses the request body as JSON and stores the result in v. If valid is true, the struct is validated after parsing.

func (*Context) JSONError added in v0.9.0

func (c *Context) JSONError(code int, message string)

JSONError writes a JSON error response with the given status code and message.

func (*Context) Next

func (c *Context) Next()

Next calls the next middleware function in the chain.

func (*Context) Param

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

Param returns the value of a URL parameter for a given key.

func (*Context) ParamFloat32 added in v0.6.0

func (c *Context) ParamFloat32(key string) (float32, error)

ParamFloat32 returns the value of a URL parameter as a float32.

func (*Context) ParamFloat64 added in v0.6.0

func (c *Context) ParamFloat64(key string) (float64, error)

ParamFloat64 returns the value of a URL parameter as a float64.

func (*Context) ParamInt added in v0.6.0

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

ParamInt returns the value of a URL parameter as an integer.

func (*Context) ParamInt64 added in v0.6.0

func (c *Context) ParamInt64(key string) (int64, error)

ParamInt64 returns the value of a URL parameter as an int64.

func (*Context) ParamUInt added in v0.6.0

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

ParamUInt returns the value of a URL parameter as a uint.

func (*Context) ParamUInt64 added in v0.6.0

func (c *Context) ParamUInt64(key string) (uint64, error)

ParamUInt64 returns the value of a URL parameter as a uint64.

func (*Context) Params

func (c *Context) Params() map[string]string

Params returns all URL parameters for the request.

func (*Context) Queries

func (c *Context) Queries() map[string][]string

Queries returns all query parameters for the request.

func (*Context) Query

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

Query returns the value of a given query parameter.

func (*Context) QueryBool added in v0.7.3

func (c *Context) QueryBool(key string) (bool, error)

QueryBool returns the value of a given query parameter as a bool.

func (*Context) QueryFloat32 added in v0.7.0

func (c *Context) QueryFloat32(key string) (float32, error)

QueryFloat32 returns the value of a given query parameter as a float32.

func (*Context) QueryFloat64 added in v0.7.0

func (c *Context) QueryFloat64(key string) (float64, error)

QueryFloat64 returns the value of a given query parameter as a float64.

func (*Context) QueryInt added in v0.7.0

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

QueryInt returns the value of a given query parameter as an int.

func (*Context) QueryInt8 added in v0.7.0

func (c *Context) QueryInt8(key string) (int8, error)

QueryInt8 returns the value of a given query parameter as an int8.

func (*Context) QueryInt32 added in v0.7.0

func (c *Context) QueryInt32(key string) (int32, error)

QueryInt32 returns the value of a given query parameter as an int32.

func (*Context) QueryInt64 added in v0.7.0

func (c *Context) QueryInt64(key string) (int64, error)

QueryInt64 returns the value of a given query parameter as an int64.

func (*Context) QueryUInt added in v0.7.0

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

QueryUInt returns the value of a given query parameter as a uint.

func (*Context) QueryUInt8 added in v0.7.0

func (c *Context) QueryUInt8(key string) (uint8, error)

QueryUInt8 returns the value of a given query parameter as a uint8.

func (*Context) QueryUInt32 added in v0.7.0

func (c *Context) QueryUInt32(key string) (uint32, error)

QueryUInt32 returns the value of a given query parameter as a uint32.

func (*Context) QueryUInt64 added in v0.7.0

func (c *Context) QueryUInt64(key string) (uint64, error)

QueryUInt64 returns the value of a given query parameter as a uint64.

func (*Context) RawBody

func (c *Context) RawBody() []byte

RawBody returns the raw request body.

func (*Context) Redirect

func (c *Context) Redirect(code int, url string)

Redirect redirects the request to a new URL with the given status code. WARNING: Do not pass user-controlled input directly. Use RedirectSafe instead.

func (*Context) RedirectSafe added in v0.11.0

func (c *Context) RedirectSafe(code int, url string, allowedHosts ...string) error

RedirectSafe performs a redirect only if the URL is a safe relative path or belongs to one of the allowed hosts.

func (*Context) Referer

func (c *Context) Referer() string

Referer returns the referer of the request.

func (*Context) RemoteAddr

func (c *Context) RemoteAddr() string

RemoteAddr returns the remote address of the request.

func (*Context) SetBody added in v0.1.5

func (c *Context) SetBody(body []byte)

SetBody sets the response body.

func (*Context) SetCookie

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

SetCookie sets a new cookie with the given key-value pair. Deprecated: Use SetCookieWithConfig for proper security attributes (HttpOnly, Secure, SameSite).

func (*Context) SetCookieWithConfig added in v0.11.0

func (c *Context) SetCookieWithConfig(config CookieConfig)

SetCookieWithConfig sets a cookie with full security configuration.

func (*Context) SetData

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

SetData sets the value of a custom data field for the context.

func (*Context) SetHeader

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

SetHeader sets the value of a given header in the response.

func (*Context) SetStatus

func (c *Context) SetStatus(code int)

SetStatus sets the HTTP status code for the response.

func (*Context) SkipFlush added in v0.3.0

func (c *Context) SkipFlush()

SkipFlush sets the skipFlush flag to true, which prevents the response buffer from being flushed.

func (*Context) Status

func (c *Context) Status() int

Status returns the HTTP status code of the response.

func (*Context) StringBody

func (c *Context) StringBody() string

StringBody returns the request body as a string.

func (*Context) Success

func (c *Context) Success(data any)

Success writes a successful response with the given data.

func (*Context) Text

func (c *Context) Text(code int, text string)

Text writes a plain text response with the given status code and format.

func (*Context) UserAgent

func (c *Context) UserAgent() string

UserAgent returns the user agent of the request.

func (*Context) XML

func (c *Context) XML(code int, obj any)

XML writes an XML response with the given status code and object.

type CookieConfig added in v0.11.0

type CookieConfig struct {
	Name     string
	Value    string
	Path     string
	Domain   string
	MaxAge   int
	Secure   bool
	HttpOnly bool
	SameSite string
}

CookieConfig holds the configuration for setting a cookie with security attributes.

type Group

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

Group represents a group of routes with a common prefix and middleware.

func (*Group) AddRoute

func (g *Group) AddRoute(method string, pattern string, handlers []HandlerFunc)

AddRoute adds a new route to the Application with the given method, pattern, and handlers. The route's path is the full prefix of the Group concatenated with the given pattern. The route's handlers are the middleware functions of the Group and its ancestors concatenated with the given handlers.

func (*Group) Delete

func (g *Group) Delete(pattern string, handlers ...HandlerFunc)

Delete adds a new DELETE route to the Application with the given pattern and handlers.

func (*Group) Get

func (g *Group) Get(pattern string, handlers ...HandlerFunc)

Get adds a new GET route to the Application with the given pattern and handlers.

func (*Group) Group

func (g *Group) Group(prefix string) *Group

Group creates a new Group with the given prefix and adds it as a child of the current Group.

func (*Group) Head

func (g *Group) Head(pattern string, handlers ...HandlerFunc)

Head adds a new HEAD route to the Application with the given pattern and handlers.

func (*Group) Options

func (g *Group) Options(pattern string, handlers ...HandlerFunc)

Options adds a new OPTIONS route to the Application with the given pattern and handlers.

func (*Group) Patch

func (g *Group) Patch(pattern string, handlers ...HandlerFunc)

Patch adds a new PATCH route to the Application with the given pattern and handlers.

func (*Group) Post

func (g *Group) Post(pattern string, handlers ...HandlerFunc)

Post adds a new POST route to the Application with the given pattern and handlers.

func (*Group) Put

func (g *Group) Put(pattern string, handlers ...HandlerFunc)

Put adds a new PUT route to the Application with the given pattern and handlers.

func (*Group) Use

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

Use adds the given middleware functions to the Group's middleware stack.

type HandlerFunc

type HandlerFunc func(*Context)

HandlerFunc is a function type that represents the actual handler function for a route.

type JSONMarshal added in v0.4.0

type JSONMarshal func(v interface{}) ([]byte, error)

type JSONUnmarshal added in v0.4.0

type JSONUnmarshal func(data []byte, v interface{}) error

type Map

type Map map[string]any

Map is a shortcut for map[string]interface{}

type Middleware added in v0.1.1

type Middleware = HandlerFunc

Middleware is an alias for HandlerFunc, representing middleware functions.

func Helmet added in v0.11.0

func Helmet() Middleware

Helmet returns a middleware that sets common security response headers.

func Logger

func Logger() Middleware

Logger returns a middleware function that logs incoming requests

func Recovery

func Recovery(handler ...HandlerFunc) Middleware

Recovery returns a middleware that recovers from panics and sends a 500 response with an error message.

Directories

Path Synopsis
examples
contextual_data command
cookie command
group command
middleware command
not_found command
ping command
recovery command
redirect command
response_body command
response_header command
routing command
static command
success_fail command
validation command

Jump to

Keyboard shortcuts

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