lightning

package module
v0.7.2 Latest Latest
Warning

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

Go to latest
Published: Mar 11, 2024 License: MIT Imports: 16 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"
)

MIME types

View Source
const (
	HeaderContentType        = "Content-Type"
	HeaderContentDisposition = "Content-Disposition"
)

Header keys

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
}

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 is a function that 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) Run

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

Run starts the HTTP server and listens for incoming requests.

func (*Application) ServeHTTP

func (app *Application) ServeHTTP(w http.ResponseWriter, req *http.Request)

ServeHTTP is the function that handles HTTP requests. It finds the matching route, creates a new Context, sets the route parameters, and executes the MiddlewareFunc chain.

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) 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. It uses the os.Executable function to get the path of the executable file, and then joins it with the root and the path after the prefix to get the full file path. If the file exists, it is served with a 200 status code using the http.ServeFile function. If the file does not exist, a 404 status code is returned with the text "Not Found".

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 // Handler function for 404 Not Found error
	EnableDebug     bool
}

type Context

type Context struct {
	App *Application
	Req *http.Request
	Res http.ResponseWriter

	Method string // HTTP method of the originReq
	Path   string // URL path of the originReq
	// contains filtered or unexported fields
}

Context represents the context of an HTTP request/response.

func NewContext added in v0.1.3

func NewContext(writer http.ResponseWriter, req *http.Request) (*Context, error)

NewContext creates a new context object with the given HTTP response writer and req.

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) Cookie

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

Cookie returns the cookie with the given name.

func (*Context) Cookies

func (c *Context) Cookies() []*http.Cookie

Cookies returns all cookies from the req.

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.

func (*Context) GetData

func (c *Context) GetData(key string) interface{}

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 interface{})

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() http.Header

Headers returns all headers for the req.

func (*Context) JSON

func (c *Context) JSON(code int, obj interface{})

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

func (*Context) JSONBody

func (c *Context) JSONBody(v interface{}, valid ...bool) error

JSONBody parses the origin request body as JSON and stores the result in v.

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 for a given key.

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 for a given key.

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 for a given key.

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 for a given key.

func (*Context) ParamString added in v0.6.0

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

ParamString returns the value of a URL parameter as a string for a given key.

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 for a given key.

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 for a given key.

func (*Context) Params

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

Params returns all URL parameters for the req.

func (*Context) Queries

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

Queries returns all query parameters for the req.

func (*Context) Query

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

Query returns the value of a given query parameter.

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) 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) 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) QueryString added in v0.7.0

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

QueryString returns the value of a given query parameter as a string.

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) 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) 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) RawBody

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

RawBody returns the raw origin request body.

func (*Context) Redirect

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

Redirect redirects the originReq to a new URL with the given status code.

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.

func (*Context) SetCustomCookie

func (c *Context) SetCustomCookie(cookie *http.Cookie)

SetCustomCookie sets a custom cookie in the response.

func (*Context) SetData

func (c *Context) SetData(key string, value interface{})

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 origin request body as a string.

func (*Context) Success

func (c *Context) Success(data interface{})

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 interface{})

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

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

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.

Jump to

Keyboard shortcuts

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