gale

package module
v1.0.0-beta2 Latest Latest
Warning

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

Go to latest
Published: Nov 14, 2024 License: MIT Imports: 30 Imported by: 4

README

Gale

A fast and easy-to-use Go router.

Installation

Create a new go project and install the package with the following command:

go get github.com/bndrmrtn/go-gale@latest

Usage

Creating and configuring a new Gale application
app := gale.New() // with default configuration
app := gale.New(&gale.Config{...}) // with custom configuration
Routing with Gale

A simple hello world response:

app.Get("/", func(c gale.Ctx) error {
	return c.Status(http.StatusOK).SendString("Hello, World!")
})

A route with a custom parameter:

app.Get("/user/{name}", func(c gale.Ctx) error {
	return c.SendString("Hello, " + c.Param("name") + "!")
})

A route with an optional parameter:

app.Get("/user/{name}?", func(c gale.Ctx) error {
	// The c.Param() second option can be a default value if the parameter is not provided
	return c.SendString("Hello, " + c.Param("name", "World") + "!")
})

Route parameter validation:

app.RegisterRouteParamValidator("webp", func(value string) (string, error) {
	if strings.HasSuffix(value, ".webp") {
		return strings.TrimSuffix(value, ".webp"), nil
	}
	return "", errors.New("invalid file")
})

Use a parameter validation:

app.Get("/images/{image@webp}", func(c gale.Ctx) error {
	return c.JSON(gale.Map{
		"image_name": c.Param("image"), // it will return the image name without the .webp extension.
	})
})

Piping a response:

app.Get("/pipe", func(c gale.Ctx) error {
	return c.Pipe(func(pw *io.PipeWriter) {
		for i := 0; i < 5; i++ {
			pw.Write([]byte(fmt.Sprintf("Streaming data chunk %d\n", i)))
			time.Sleep(1 * time.Second) // Simulate some delay
		}
	})
})
Middleware with Gale

All middleware function comes after the main handler with Gale:

app.Get(path string, handler gale.HandlerFunc, middlewares ...gale.MiddlewareFunc)

A simple middleware:

app.Get("/secret", func(c gale.Ctx) error {
		return c.SendString("Secret data")
	}, func(c gale.Ctx) (bool, error) {
		if c.URL().Query().Get("auth") != "123" {
			return c.Break().Status(http.StatusUnauthorized).SendString("Unauthorized")
		}
		return nil
})
Websockets with Gale

Gale uses https://github.com/coder/websocket package for handling websocket connections. We wrapped our Ctx and *websocket.Conn into a WSConn struct for easier usage.

You can create a websocket connection like this:

server := gale.NewWSServer(context.Background())

// This must be set. Here you can define your own websocket connection handler.
server.OnMessage(func(s gale.WSServer, conn gale.WSConn, msg []byte) error {})

You don't have to set up loops are anything. The server will handle everything for you. You only need to handle the incoming message and broadcast to your desired clients.

app.WS("/ws", func(c WSConn) {
	// Handle the connection here with a loop by itself or add it to the server.
	server.AddConn(c)
})

⚠️ Attention: The WS method is just like a Get method with a special adapter used for websocket connections. You can't specify the same route for both Get and WS methods.

Sessions with Gale

Gale supports sessions. You can edit the default configuration or use it as it is. By default, Gale uses uuidv4 and cookies to manage Session ID-s. Sessions are stored in an in-memory store. You can change the store by implementing the gale.SessionStore interface.

Setting a session:

app.Get("/session-set", func(c gale.Ctx) error {
	session := c.Session()
	session.Set("key", []byte("value"))
	return c.SendString("Session created")
})

Getting a session:

app.Get("/session-get", func(c gale.Ctx) error {
	session := c.Session()
	value, _ := session.Get("key")
	return c.Send(value)
})

It also supports session.Delete("key") and session.Destroy() methods.

Hooks with Gale

Gale supports hooks. Hooks are functions that are called on a specific event. You can register a hook for a specific event.

app.Hook(gale.PreRequestHook, func(c Ctx) error {
	// A simple hook handler with an error return.
	return nil // or just return nil to continue the request chain.
})

You can also use gale.PostRequestHook that runs after the request handled.

Documentation

Index

Constants

View Source
const (
	ContentTypeJSON      = "application/json"
	ContentTypeText      = "text/plain"
	ContentTypeHTML      = "text/html"
	ContentTypeXML       = "application/xml"
	ContentTypeForm      = "application/x-www-form-urlencoded"
	ContentTypeMultipart = "multipart/form-data"
)
View Source
const Version = "1.0.0-beta"

Version is the current version of Gale

Variables

This section is empty.

Functions

func NewError

func NewError(statusCode int, err string) error

Types

type BodyCtx

type BodyCtx interface {
	// Parse the request body to any by the Content-Type header
	Parse(v any) error
	// ParseJSON parses the request body as JSON
	ParseJSON(v any) error
	// ParseXML parses the request body as XML
	ParseXML(v any) error
	// ParseForm parses the request body as form
	ParseForm(v any) error
	// File returns a file from the request
	File(name string, maxSize ...int) (multipart.File, *multipart.FileHeader, error)
}

BodyCtx is the context of the request body

type CompleteRouter

type CompleteRouter interface {
	Router
	RouterParamValidator
	// Dump writes the routes to the console.
	Dump()
	// Export is an alias to exportRoutes.
	Export() []Route
	// contains filtered or unexported methods
}

CompleteRouter is an interface that combines the Router and RouterParamValidator interfaces.

type Config

type Config struct {
	// ErrorHandler handles the request errors
	ErrorHandler func(c Ctx, err error) error
	// NotFoundHandler handles the not found requests
	NotFoundHandler func(c Ctx) error
	// Mode is the application mode
	// default is development
	Mode Mode

	Views     *ViewConfig
	Session   *SessionConfig
	Websocket *WSConfig
}

Config is the configuration of the Gale application

type CookieCtx

type CookieCtx interface {
	// Get returns a cookie by name
	Get(name string) (*http.Cookie, error)
	// Set sets a cookie
	Set(cookie *http.Cookie)
	// Delete deletes a cookie by name
	Delete(name string)
}

CookieCtx is the context of the request cookies

type Ctx

type Ctx interface {
	ID() string

	// Method returns the request method
	Method() string
	// URL returns the request URL
	URL() *url.URL
	// Path returns the request path
	Path() string
	// Params returns all route params
	Params() map[string]string
	// Param returns a route param by name
	Param(name string, defaultValue ...string) string
	// ParamInt returns a route param by name as int
	ParamInt(name string, defaultValue ...int) (int, error)

	// ResponseWriter returns the http.ResponseWriter
	ResponseWriter() http.ResponseWriter
	// Request returns the http.Request
	Request() *http.Request
	// Context returns the Request Context
	Context() context.Context
	// App returns the Gale application
	App() *Gale
	// IP returns the client IP
	IP() string

	// Headers
	// Header returns a HeaderCtx to add response header and get request header
	Header() HeaderCtx
	// Cookie returns a CookieCtx to get and set cookies
	Cookie() CookieCtx
	// Session returns a SessionCtx to get and set session data (if session is enabled in the configuration)
	Session() SessionCtx
	// ContentType sets the response content type
	ContentType(t string) Ctx

	// Status sets the response status code
	Status(code int) Ctx
	// Send sends the output as a byte slice
	Send([]byte) error
	// SendString sends the output as a string
	SendString(s string) error
	// JSON sends the output as a JSON
	JSON(data any) error
	// XML sends the output as a XML
	XML(data any) error
	// SendFile sends a file as a response
	SendFile(path string) error
	// Pipe sends the output as a stream
	Pipe(pipe func(pw *io.PipeWriter)) error
	// Format sends the output in the format specified in the Accept header
	Format(data any) error
	// Redirect redirects the request to the specified URL
	Redirect(to string) error

	Spark(component spark.Component) error

	// Body returns a BodyCtx to parse the request body
	Body() BodyCtx

	// Get returns a stored value by key
	Get(key string) any
	// Set stores a value by key in the context (useful for middleware)
	// note: the value only exists in the current request
	Set(key string, value any)
	// Locals returns all stored values
	Locals() map[string]any

	// Break stops the request chain execution
	Break() Ctx
	// Route returns the current route
	Route() Route
	// contains filtered or unexported methods
}

Ctx is the context of the request

type EasyFastHandlerFunc

type EasyFastHandlerFunc func(c Ctx) (any, error)

type Error

type Error struct {
	Err    string
	Status int
}

func (*Error) Error

func (h *Error) Error() string

type Gale

type Gale struct {
	CompleteRouter
	// contains filtered or unexported fields
}

func New

func New(conf ...*Config) *Gale

New creates a new Gale application with the given configuration

func (*Gale) Config

func (g *Gale) Config() *Config

Config returns the configuration of the Gale application

func (*Gale) Hook

func (g *Gale) Hook(hook GaleHook, fns ...func(c Ctx) error)

Hook registers a hook for the given hook type Note: Hooks are methods that are executed before or after a request is processed

func (*Gale) PublicDir

func (g *Gale) PublicDir(path string) error

PublicDir sets the public directory for the Gale application

func (*Gale) Router

func (g *Gale) Router() CompleteRouter

Router returns the router of the Gale application

func (*Gale) Serve

func (g *Gale) Serve(listenAddr string) error

Serve starts the Gale server on the given address

func (*Gale) ServeTLS

func (g *Gale) ServeTLS(listenAddr, certFile, keyFile string) error

ServeTLS starts the Gale server on the given address with TLS

func (*Gale) Use

func (g *Gale) Use(fn UseExtension)

Use registers an extension for the Gale application

type GaleHook

type GaleHook int
const (
	// PreRequestHook is executed when the router found a match.
	PreRequestHook GaleHook = iota
	// PostRequestHook is executed after the route handler.
	PostRequestHook GaleHook = iota
	// EveryRequestHook is executed on every request.
	EveryRequestHook GaleHook = iota
)

type HandlerFunc

type HandlerFunc func(c Ctx) error

HandlerFunc is a function that handles a request.

func Adaptor

func Adaptor(fn http.HandlerFunc) HandlerFunc

Adaptor converts the standard http.HandlerFunc to a gale.HandlerFunc

func EasyFastAdaptor

func EasyFastAdaptor(fn EasyFastHandlerFunc) HandlerFunc

EasyFastAdaptor is a fast way to just dump data or error as a response without using the Ctx send methods

type HeaderCtx

type HeaderCtx interface {
	// Add adds a header to the response
	Add(key, value string)
	// Get returns a header from the request
	Get(key string) string
	// GetAll returns all headers from the request
	GetAll() map[string][]string
}

HeaderCtx is the context of the request headers

type Map

type Map map[string]any

Map is a map[string]any alias to make it more readable

type MemoryStore

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

MemoryStore is an in-memory session storage.

func (*MemoryStore) Close

func (s *MemoryStore) Close() error

func (*MemoryStore) Del

func (s *MemoryStore) Del(key string) error

func (*MemoryStore) Exists

func (s *MemoryStore) Exists(key string) bool

func (*MemoryStore) Get

func (s *MemoryStore) Get(key string) ([]byte, error)

func (*MemoryStore) Set

func (s *MemoryStore) Set(key string, value []byte) error

func (*MemoryStore) SetEx

func (s *MemoryStore) SetEx(key string, value []byte, expiry time.Duration) error

type MiddlewareFunc

type MiddlewareFunc func(c Ctx) error

MiddlewareFunc is a function that is executed before the handler.

type Mode

type Mode string

Mode is the application mode

const (
	Production  Mode = "production"
	Development Mode = "development"
)

type Route

type Route interface {
	Name(name string)
	GetName() string
	Method() string
	Path() string
	NormalizedPaths() []string

	Handler() HandlerFunc
	Middlewares() []MiddlewareFunc
	// contains filtered or unexported methods
}

type RouteParamValidatorFunc

type RouteParamValidatorFunc func(value string) (string, error)

RouteParamValidatorFunc is a function that validates a route parameter.

type RoutePart

type RoutePart struct {
	Static     bool     `json:"static"`
	Value      string   `json:"value"`
	Validators []string `json:"validators,omitempty"`
}

type Router

type Router interface {
	// Get registers a new GET route for a path with matching handler and optional middlewares.
	Get(path string, handler HandlerFunc, middlewares ...MiddlewareFunc) Route
	// Post registers a new POST route for a path with matching handler and optional middlewares.
	Post(path string, handler HandlerFunc, middlewares ...MiddlewareFunc) Route
	// Put registers a new PUT route for a path with matching handler and optional middlewares.
	Put(path string, handler HandlerFunc, middlewares ...MiddlewareFunc) Route
	// Delete registers a new DELETE route for a path with matching handler and optional middlewares.
	Delete(path string, handler HandlerFunc, middlewares ...MiddlewareFunc) Route
	// Patch registers a new PATCH route for a path with matching handler and optional middlewares.
	Patch(path string, handler HandlerFunc, middlewares ...MiddlewareFunc) Route
	// Options registers a new OPTIONS route for a path with matching handler and optional middlewares.
	Options(path string, handler HandlerFunc, middlewares ...MiddlewareFunc) Route
	// All registers a new route for a path with matching handler and optional middlewares.
	All(path string, handler HandlerFunc, middlewares ...MiddlewareFunc) Route
	// Add registers a new route for a path with matching handler and optional middlewares.
	Add(method, path string, handler HandlerFunc, middlewares ...MiddlewareFunc) Route

	// WS registers a new WebSocket route for a path with matching handler and optional middlewares.
	// Note: WebSocket routes should have a different path then GET routes.
	WS(path string, handler WSHandlerFunc, middlewares ...MiddlewareFunc) Route

	// Group creates a new router group with a common prefix and optional middlewares.
	Group(prefix string, middlewares ...MiddlewareFunc) Router
}

Router is an interface that defines the methods for registering routes.

type RouterParamValidator

type RouterParamValidator interface {
	// RouterParamValidator is an interface that allows you to register custom route parameter validators.
	// default validators: int, bool, uuid, alpha, alphanumeric.
	RegisterRouteParamValidator(name string, fn RouteParamValidatorFunc)
}

RouterParamValidator is an interface that allows you to register custom route parameter validators.

type SessionConfig

type SessionConfig struct {
	// Enabled is a flag to enable or disable the session
	// session is enabled by default
	Enabled bool
	// TokenFunc is a function to get the session token
	// by default it generates a new token if not exists, and stores it in a cookie named "session"
	TokenFunc func(c Ctx) (string, error)
	// TokenExpire is the session token expiration time
	// by default it is 12 hours
	// tokens are renewed at each modification
	TokenExpire time.Duration
	// Store is the session storage
	// by default it uses the MemStorage, an in-memory storage
	Store SessionStore
}

SessionConfig is the configuration of the session

type SessionCtx

type SessionCtx interface {
	// Get returns a session value by key
	Get(key string) ([]byte, error)
	// Set sets a session value by key
	Set(key string, value []byte) error
	// Delete deletes a session value by key
	Delete(key string) error
	// Destroy destroys the session
	Destroy() error

	// From returns a session from another session id
	From(id string) SessionCtx
	// ID returns the session id
	ID() string
	// SetID sets the session id
	SetID(s string) SessionCtx
}

SessionCtx is the context of the request session

type SessionStore

type SessionStore interface {
	Get(key string) ([]byte, error)
	Exists(key string) bool
	Set(key string, value []byte) error
	SetEx(key string, value []byte, expiry time.Duration) error
	Del(key string) error
}

SessionStore is an interface for session storage.

func NewMemStorage

func NewMemStorage(gcInterval ...time.Duration) SessionStore

NewMemStorage creates a new MemoryStore.

type UI

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

func NewUIDevtools

func NewUIDevtools() *UI

func (*UI) Register

func (u *UI) Register(g *Gale)

type UIRouteLog

type UIRouteLog struct {
	Method string
	Path   string
	Name   string
	IP     string
	Time   time.Time
}

type UseExtension

type UseExtension interface {
	Register(g *Gale)
}

type ViewConfig

type ViewConfig struct {
	Views *template.Template
}

type WSConfig

type WSConfig struct {
	Timeout time.Duration

	AcceptOptions *websocket.AcceptOptions
}

WSConfig is the configuration of the websocket

type WSConn

type WSConn interface {
	Ctx() Ctx
	Conn() *websocket.Conn
	Close() error

	Send(data []byte) error
	SendJSON(v any) error
	// contains filtered or unexported methods
}

type WSHandlerFunc

type WSHandlerFunc func(conn WSConn)

WSHandlerFunc is a function that handles a WebSocket request.

type WSMessageHandler

type WSMessageHandler func(s WSServer, conn WSConn, msg []byte) error

type WSServer

type WSServer interface {
	// AddConnection adds a new connection to the server.
	AddConn(conn WSConn)
	// RemoveConnection removes a connection from the server.
	RemoveConn(conn WSConn)
	// RemoveConnection removes a connection from the server.
	Broadcast(msg []byte) int
	// BroadcastFunc sends a message to all connections that satisfy the condition.
	BroadcastFunc(msg []byte, fn func(conn WSConn) bool) int
	// BroadcastTo sends a message to a specific connection.
	BroadcastTo(msg []byte, conns ...WSConn) int

	// OnMessage sets the function to be called when a message is received.
	OnMessage(fn WSMessageHandler)

	// Close closes the server.
	Close() error
	// contains filtered or unexported methods
}

WSServer is the interface that wraps the basic methods for a websocket server.

func NewWSServer

func NewWSServer(ctx context.Context) WSServer

Jump to

Keyboard shortcuts

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