pulse

package module
v0.3.5 Latest Latest
Warning

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

Go to latest
Published: Sep 5, 2024 License: MIT Imports: 17 Imported by: 0

README

Here is the updated README with the new information about the database changes:

Pulse Web Framework

Pulse is a lightweight and flexible web framework for building web applications and APIs in Go. It provides a structured way to manage HTTP requests and responses, integrates middleware, and supports context management and direct database integration, making web development in Go more efficient and organized.

Table of Contents

Features

  • Context Management: Manage request, response, parameters, headers, and cookies.
  • Routing: Register routes with support for all HTTP methods.
  • Middleware: Use and create middleware to handle cross-cutting concerns.
  • Request Handling: Bind and validate JSON, form, and multipart form data.
  • Response Handling: Send plain text, JSON, HTML responses, and serve files.
  • Error Handling: Centralized error handling.
  • Database Integration: Easy setup and use of MySQL, PostgreSQL, and SQLite databases.

Installation

To install Pulse, use go get:

go get git.trcreatives.com/triegebauer/pulse

Quick Start

Here's a simple example to get you started with Pulse:

package main

import (
	"git.trcreatives.com/triegebauer/pulse"
)

func main() {
	app := pulse.New()

	app.Get("/", func(c *pulse.Context) error {
		return c.SendString(pulse.StatusOK, "Hello, Pulse!")
	})

	app.Start(":8080")
}

Usage

Context Management

The Context struct provides methods to interact with the HTTP request, response, and other utilities.

func handler(c *pulse.Context) error {
	req := c.GetRequest()
	res := c.GetResponse()
	params := c.GetParams()

	// Do something with req, res, or params...

	return nil
}
Routing

Register routes with Pulse using the available methods (Get, Post, Put, Delete, Patch, Options, Head).

app.Get("/hello", func(c *pulse.Context) error {
	return c.SendString(pulse.StatusOK, "Hello, World!")
})
Middleware

Middleware can be used to modify or handle requests before they reach the final handler.

app.Use(middleware.Logging(middleware.DefaultLoggingConfig))
Request Handling

Bind and validate JSON, form, and multipart form data.

type User struct {
	Name  string `json:"name" validate:"required"`
	Email string `json:"email" validate:"required,email"`
}

app.Post("/user", func(c *pulse.Context) error {
	var user User
	if err := c.BindJSON(&user); err != nil {
		return c.SendString(pulse.StatusBadRequest, err.Error())
	}

	// Process user...

	return c.SendJSON(pulse.StatusOK, user)
})
Response Handling

Send different types of responses including plain text, JSON, and HTML.

app.Get("/json", func(c *pulse.Context) error {
	data := map[string]interface{}{"message": "Hello, JSON!"}
	return c.SendJSON(pulse.StatusOK, data)
})

app.Get("/html", func(c *pulse.Context) error {
	html := "<h1>Hello, HTML!</h1>"
	return c.SendHTML(pulse.StatusOK, html)
})

Set, get and delete cookies.

app.Get("/set-cookie", func(c *pulse.Context) error {
	c.SetCookie(pulse.CookieConfig{
		Name:     "token",
		Value:    "abc123",
		MaxAge:   3600,
		Path:     "/",
		Secure:   true,
		HttpOnly: true,
		SameSite: pulse.SameSiteStrictMode,
	})
	return c.SendString(pulse.StatusOK, "Cookie set!")
})

app.Get("/get-token", func(c *pulse.Context) error {
	tokenCookie, err := c.GetCookie("token")
	if err != nil {
		return err
	}
	return c.SendString(pulse.StatusOK, "Token: "+tokenCookie.Value)
})

app.Get("/logout", func(c *pulse.Context) error {
	if err := c.DeleteCookie("token"); err != nil {
		return err
	}
	return c.Redirect("/login")
})
Error Handling

Define a centralized error handler.

app.SetErrorHandler(func(err error, c *pulse.Context) {
	c.GetLogger().Error("Error: %v", err)
	c.SendString(pulse.StatusInternalServerError, "Internal Server Error")
})
Database Integration

Pulse provides easy integration with MySQL, PostgreSQL, and SQLite databases.

Database Configuration

First, define your database configuration using the database.Config struct.

dbConfig := database.Config{
	Type:     database.TypeMySQL,
	DBName:   "mydb",
	Host:     "localhost",
	Port:     3306,
	Username: "user",
	Password: "password",
}

For SQLite, you need to set the DBFilePath instead of Host, Port, Username, and Password.

dbConfig := database.Config{
	Type:       database.TypeSQLite,
	DBFilePath: "path/to/database.db",
}
Setting Up the Database

Next, use the WithDatabase method to set up the database connection in your Pulse application.

app := pulse.New().WithDatabase(dbConfig)
Using the Database in Handlers

You can access the database connection from the context within your route handlers.

app.Get("/users", func(c *pulse.Context) error {
	var users []User
	err := c.DB().Select(&users, "SELECT * FROM users")
	if err != nil {
		return c.SendString(pulse.StatusInternalServerError, "Database error: " + err.Error())
	}
	return c.SendJSON(pulse.StatusOK, users)
})
Database Migrations

Pulse supports database migrations using the migrate package.

Running Migrations

You can run migrations using the MigrateUp and MigrateDown methods.

err := app.DB().MigrateUp("path/to/migrations")
if err != nil {
	log.Fatalf("Migration up failed: %v", err)
}

err = app.DB().MigrateDown("path/to/migrations")
if err != nil {
	log.Fatalf("Migration down failed: %v", err)
}
WebSocket Management

Pulse provides built-in support for WebSocket connections, allowing you to handle real-time communication efficiently. You can set up WebSocket handlers, manage connections, and broadcast messages to connected clients.

Setting Up a WebSocket Handler

To set up a WebSocket handler, use the WebSocket method to define an endpoint and apply optional middleware. Here's an example of how to configure a WebSocket endpoint:

app := pulse.New()
app.WebSocket("/chat") // Creates a public endpoint /chat where a user can connect
app.WebSocket("/chat", your_middleware) // You can also add your own middleware into it to secure some websocket endpoints
app.Start(":8000")
Broadcasting Messages

You can broadcast messages to all clients connected to a specific WebSocket endpoint or to all connected clients across endpoints.

// Broadcast to a specific endpoint
app.Get("/broadcast", func(c *pulse.Context) error {
	message := []byte("Hello, WebSocket!")
	c.GetEventManager().Broadcast("/ws", message)
	return c.SendString(pulse.StatusOK, "Message broadcasted!")
})

// Broadcast to all clients
app.Get("/broadcast-all", func(c *pulse.Context) error {
	message := []byte("Hello, everyone!")
	c.GetEventManager().BroadcastToAll(message)
	return c.SendString(pulse.StatusOK, "Message broadcasted to all!")
})

Middleware Provided

Pulse comes with several built-in middleware:

  • CORS: Handles Cross-Origin Resource Sharing.
  • Logging: Logs request details and execution time.
  • Recovery: Recovers from panics to prevent server crashes.
  • RequestID: Assigns a unique ID to each request for tracking and logging.

Contributing

Contributions are welcome! Please fork the repository and submit a pull request.

License

Pulse is licensed under the MIT License. See the LICENSE file for details.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Context

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

Context holds the request, response, and various utilities for handling HTTP requests.

func (*Context) BindForm

func (c *Context) BindForm(v interface{}) error

BindForm reads the Form body from the request and unmarshals it into the provided value.

func (*Context) BindJSON

func (c *Context) BindJSON(v interface{}) error

BindJSON reads the JSON body from the request and unmarshals it into the provided value.

func (*Context) BindMultipartForm

func (c *Context) BindMultipartForm(v interface{}, maxMemory int64) error

BindMultipartForm reads the multipart form body from the request and unmarshals it into the provided value.

func (*Context) Broadcast added in v0.2.0

func (c *Context) Broadcast(endpoint string, message []byte)

Broadcast sends a message to all connected WebSocket clients for a specific endpoint.

func (*Context) BroadcastToAll added in v0.2.0

func (c *Context) BroadcastToAll(message []byte)

BroadcastToAll sends a message to all connected WebSocket clients across all endpoints.

func (*Context) Cookie added in v0.3.3

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

GetCookie retrieves a specific cookie by name from the request.

func (*Context) DB added in v0.3.1

func (c *Context) DB() *sqlx.DB

DB returns the database associated with the context.

func (*Context) DeleteCookie added in v0.3.2

func (c *Context) DeleteCookie(name string) error

DeleteCookie removes a cookie from the clients browser

func (*Context) Get

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

Get retrieves a value from the context.Context using a key.

func (*Context) GetContext

func (c *Context) GetContext() context.Context

GetContext returns the context.Context associated with the context.

func (*Context) GetEventManager added in v0.2.0

func (c *Context) GetEventManager() *events.EventManager

GetEventManager returns the event manager associated with the context.

func (*Context) GetHeader

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

GetHeader retrieves the value of a specific request header.

func (*Context) GetLogger

func (c *Context) GetLogger() *logger.Logger

GetLogger returns the logger associated with the context.

func (*Context) GetParam

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

GetParam retrieves a specific URL parameter by key.

func (*Context) GetParams

func (c *Context) GetParams() httprouter.Params

GetParams returns the URL parameters from the router associated with the context.

func (*Context) GetQueryParam

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

GetQueryParam retrieves a specific query parameter by key from the request URL.

func (*Context) GetRequest

func (c *Context) GetRequest() *http.Request

GetRequest returns the HTTP request associated with the context.

func (*Context) GetResponse

func (c *Context) GetResponse() http.ResponseWriter

GetResponse returns the HTTP response writer associated with the context.

func (*Context) Redirect

func (c *Context) Redirect(status StatusCode, url string) error

Redirect performs an HTTP redirect to the specified URL with the given status code.

func (*Context) RenderTempl

func (c *Context) RenderTempl(component templ.Component) error

RenderTempl renders a templ template

func (*Context) SendFile

func (c *Context) SendFile(filePath string) error

SendFile serves a file located at the specified file path.

func (*Context) SendHTML

func (c *Context) SendHTML(status StatusCode, data string) error

SendHTML sends an HTML response with the given status code.

func (*Context) SendJSON

func (c *Context) SendJSON(status StatusCode, data interface{}) error

SendJSON sends a JSON response with the given status code.

func (*Context) SendString

func (c *Context) SendString(status StatusCode, data string) error

SendString sends a plain text response with the given status code.

func (*Context) Set

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

Set stores a value in the context.Context using a key.

func (*Context) SetContext

func (c *Context) SetContext(ctx context.Context)

SetContext updates the context.Context associated with the context.

func (*Context) SetCookie

func (c *Context) SetCookie(config CookieConfig)

SetCookie sets a cookie in the response.

func (*Context) SetHeader

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

SetHeader sets the value of a specific response header.

func (*Context) Status

func (c *Context) Status(status StatusCode)

Status sets the HTTP status code for the response.

type ContextType

type ContextType string

type CookieConfig

type CookieConfig struct {
	// Name is the name of the cookie.
	Name string

	// Value is the value of the cookie.
	Value string

	// MaxAge specifies the maximum age in seconds for the cookie.
	// A zero or negative value means that the cookie is a session cookie.
	MaxAge int

	// Path specifies the URL path that the cookie is valid for.
	Path string

	// Domain specifies the domain that the cookie is valid for.
	Domain string

	// Secure indicates whether the cookie should only be sent over secure (HTTPS) connections.
	Secure bool

	// HttpOnly indicates whether the cookie is inaccessible to JavaScript (i.e., client-side scripts).
	HttpOnly bool

	// SameSite specifies the SameSite attribute for the cookie, controlling cross-site request behavior.
	SameSite SameSite
}

CookieConfig holds configuration options for setting cookies.

type ErrorHandler

type ErrorHandler func(error, *Context) error

ErrorHandler defines a function type for handling errors in the context of an HTTP request. It takes an error and a Context object, and returns an error which can be used for additional processing.

type Handler

type Handler func(c *Context) error

Handler is a function type for processing HTTP requests. It takes a *Context and returns an error.

type Json

type Json = map[string]interface{}

JSON type alias for map[string]interface{}

type Middleware

type Middleware func(Handler) Handler

Middleware is a function type that wraps a Handler. It takes a Handler as input and returns a new Handler.

type Pulse

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

Pulse represents the main application struct with middleware, router, database, and logger.

func New

func New() *Pulse

New initializes a new Pulse instance with default settings.

func (*Pulse) Delete

func (p *Pulse) Delete(path string, h Handler, m ...Middleware)

Register HTTP methods with handlers and optional route-specific middleware.

func (*Pulse) Get

func (p *Pulse) Get(path string, h Handler, m ...Middleware)

func (*Pulse) GetDatabase added in v0.2.2

func (p *Pulse) GetDatabase() *database.Database

GetDatabase returns the database connected to the pulse app

func (*Pulse) GetEventManager added in v0.2.2

func (p *Pulse) GetEventManager() *events.EventManager

GetEventManager returns the event manager in the pulse app

func (*Pulse) GetLogger added in v0.3.1

func (p *Pulse) GetLogger() *logger.Logger

GetLogger returns the logger in the pulse app

func (*Pulse) Head

func (p *Pulse) Head(path string, h Handler, m ...Middleware)

func (*Pulse) Options

func (p *Pulse) Options(path string, h Handler, m ...Middleware)

func (*Pulse) Patch

func (p *Pulse) Patch(path string, h Handler, m ...Middleware)

func (*Pulse) Post

func (p *Pulse) Post(path string, h Handler, m ...Middleware)

func (*Pulse) Put

func (p *Pulse) Put(path string, h Handler, m ...Middleware)

func (*Pulse) SetErrorHandler

func (p *Pulse) SetErrorHandler(errorHandler ErrorHandler)

SetErrorHandler sets a new error handler in the Pulse struct.

func (*Pulse) SetLogger

func (p *Pulse) SetLogger(config logger.Config)

SetLogger configures a new logger, closing the existing one if necessary.

func (*Pulse) Start

func (p *Pulse) Start(listenAddr string) error

Start begins listening for incoming HTTP requests on the specified address.

func (*Pulse) Static added in v0.1.4

func (p *Pulse) Static(basePath string, directoryPath string)

Static sets up a handler to serve static files from the specified directory.

func (*Pulse) Use

func (p *Pulse) Use(m ...Middleware)

Use adds global middleware to be applied to all routes.

func (*Pulse) WebSocket added in v0.2.0

func (p *Pulse) WebSocket(endpoint string, m ...Middleware)

WebSocketHandler sets up a WebSocket handler with optional middleware.

func (*Pulse) WithDatabase

func (p *Pulse) WithDatabase(config database.Config) *Pulse

WithDatabase sets up the database connection using the provided config.

type SameSite

type SameSite int

SameSite represents the SameSite attribute for cookies, which controls whether and when cookies are sent with cross-site requests.

const (
	// SameSiteDefaultMode allows the browser to choose the SameSite policy
	// based on its own rules and defaults.
	SameSiteDefaultMode SameSite = iota + 1

	// SameSiteLaxMode allows cookies to be sent with top-level navigations
	// and will be sent with GET requests from third-party contexts.
	SameSiteLaxMode

	// SameSiteStrictMode ensures cookies are only sent in a first-party context,
	// and not sent with requests from other sites.
	SameSiteStrictMode

	// SameSiteNoneMode allows cookies to be sent with cross-site requests,
	// but requires the Secure attribute to be set.
	SameSiteNoneMode
)

type StatusCode

type StatusCode int

StatusCode represents HTTP status codes.

const (
	// StatusContinue indicates that the initial part of a request has been received and has not yet been rejected by the server.
	StatusContinue StatusCode = 100

	// StatusSwitchingProtocols indicates that the server is switching protocols as requested by the client.
	StatusSwitchingProtocols StatusCode = 101
)
const (
	// StatusOK indicates that the request was successful.
	StatusOK StatusCode = 200

	// StatusCreated indicates that the request was successful and a resource was created.
	StatusCreated StatusCode = 201

	// StatusAccepted indicates that the request has been accepted for processing, but the processing is not yet complete.
	StatusAccepted StatusCode = 202

	// StatusNonAuthoritative indicates that the request was successful, but the response is from a different source than the original server.
	StatusNonAuthoritative StatusCode = 203

	// StatusNoContent indicates that the request was successful, but there is no content to send in the response.
	StatusNoContent StatusCode = 204

	// StatusResetContent indicates that the request was successful, but the client should reset the document view.
	StatusResetContent StatusCode = 205

	// StatusPartialContent indicates that the server is delivering only part of the resource due to a range header sent by the client.
	StatusPartialContent StatusCode = 206
)
const (
	// StatusMultipleChoices indicates that there are multiple options for the resource the client may follow.
	StatusMultipleChoices StatusCode = 300

	// StatusMovedPermanently indicates that the resource has been moved permanently to a new URL.
	StatusMovedPermanently StatusCode = 301

	// StatusFound indicates that the resource resides temporarily under a different URL.
	StatusFound StatusCode = 302

	// StatusSeeOther indicates that the response to the request can be found under another URL using the GET method.
	StatusSeeOther StatusCode = 303

	// StatusNotModified indicates that the resource has not been modified since the last request.
	StatusNotModified StatusCode = 304

	// StatusUseProxy indicates that the requested resource must be accessed through a proxy.
	StatusUseProxy StatusCode = 305

	// StatusTemporaryRedirect indicates that the request should be redirected temporarily.
	StatusTemporaryRedirect StatusCode = 307

	// StatusPermanentRedirect indicates that the request should be redirected permanently.
	StatusPermanentRedirect StatusCode = 308
)
const (
	// StatusBadRequest indicates that the server could not understand the request due to invalid syntax.
	StatusBadRequest StatusCode = 400

	// StatusUnauthorized indicates that the request requires user authentication.
	StatusUnauthorized StatusCode = 401

	// StatusPaymentRequired indicates that payment is required to access the requested resource.
	StatusPaymentRequired StatusCode = 402

	// StatusForbidden indicates that the server understood the request but refuses to authorize it.
	StatusForbidden StatusCode = 403

	// StatusNotFound indicates that the requested resource could not be found.
	StatusNotFound StatusCode = 404

	// StatusMethodNotAllowed indicates that the request method is not allowed for the requested resource.
	StatusMethodNotAllowed StatusCode = 405

	// StatusNotAcceptable indicates that the server cannot produce a response matching the list of acceptable values defined in the request's headers.
	StatusNotAcceptable StatusCode = 406

	// StatusProxyAuthRequired indicates that the client must authenticate itself to use a proxy.
	StatusProxyAuthRequired StatusCode = 407

	// StatusRequestTimeout indicates that the server timed out waiting for the request.
	StatusRequestTimeout StatusCode = 408

	// StatusConflict indicates that the request could not be processed due to a conflict in the request.
	StatusConflict StatusCode = 409

	// StatusGone indicates that the resource requested is no longer available and will not be available again.
	StatusGone StatusCode = 410

	// StatusLengthRequired indicates that the request is missing a Content-Length header field.
	StatusLengthRequired StatusCode = 411

	// StatusPreconditionFailed indicates that one or more conditions in the request header fields were not met.
	StatusPreconditionFailed StatusCode = 412

	// StatusPayloadTooLarge indicates that the request is larger than the server is willing or able to process.
	StatusPayloadTooLarge StatusCode = 413

	// StatusURITooLong indicates that the URI provided was too long for the server to process.
	StatusURITooLong StatusCode = 414

	// StatusUnsupportedMediaType indicates that the server refuses to accept the request because the resource is in a format not supported by the server.
	StatusUnsupportedMediaType StatusCode = 415

	// StatusRangeNotSatisfiable indicates that the server cannot provide the requested range of the resource.
	StatusRangeNotSatisfiable StatusCode = 416

	// StatusExpectationFailed indicates that the server cannot meet the requirements of the Expect request-header field.
	StatusExpectationFailed StatusCode = 417
)
const (
	// StatusInternalServerError indicates that the server encountered an unexpected condition that prevented it from fulfilling the request.
	StatusInternalServerError StatusCode = 500

	// StatusNotImplemented indicates that the server does not support the functionality required to fulfill the request.
	StatusNotImplemented StatusCode = 501

	// StatusBadGateway indicates that the server, while acting as a gateway or proxy, received an invalid response from the upstream server.
	StatusBadGateway StatusCode = 502

	// StatusServiceUnavailable indicates that the server is currently unable to handle the request due to temporary overload or maintenance.
	StatusServiceUnavailable StatusCode = 503

	// StatusGatewayTimeout indicates that the server, while acting as a gateway or proxy, did not receive a timely response from the upstream server.
	StatusGatewayTimeout StatusCode = 504

	// StatusHTTPVersionNotSupported indicates that the server does not support the HTTP protocol version that was used in the request.
	StatusHTTPVersionNotSupported StatusCode = 505
)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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