hop

package module
v2.0.0-alpha.2 Latest Latest
Warning

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

Go to latest
Published: Apr 7, 2025 License: Apache-2.0 Imports: 18 Imported by: 0

README

Hop - Experimental

⚠️ EXPERIMENTAL: This framework is under active development and the API changes frequently. Not recommended for production use unless you're willing to vendor the code.

Hop is an experimental, modular web application framework for Go, designed for building server-side rendered applications with HTMX integration.

This is more of a test bed for ideas than a production-ready framework. Use at your own risk.

Warning

This is not a general-purpose web framework. It was built for specific use cases and may not suit your needs. Consider using established frameworks like Chi, Echo, Gin, or Fiber for production applications.

Features

  • 🧩 Modular architecture with plugin system
  • 📝 Template rendering with layouts and partials
  • 🔄 Built-in HTMX support
  • 📦 Session management
  • 🎯 Event dispatching
  • 🛣️ HTTP routing with middleware
  • 📋 Configuration management
  • 📝 Structured logging

Quick Start

TBD

package main

import (
    "context"
    "log"

    "github.com/patrickward/hop/v2"
	
   "github.com/<owner>/<project>/internal/app"     
)

func main() {
	// Load configuration from somewhere
	cfg, err := app.NewConfigFromEnv(envPrefix)
	
	// Create app
	appCfg := hop.AppConfig{
		Environment:           cfg.Environment,
		Host:                  cfg.ServerHost,
		Port:                  cfg.ServerPort,
		Handler:               mux,
		IdleTimeout:           cfg.ServerIdleTimeout,
		ReadTimeout:           cfg.ServerReadTimeout,
		WriteTimeout:          cfg.ServerWriteTimeout,
		ShutdownTimeout:       cfg.ServerShutdownTimeout,
		Logger:                logger,
		SessionStore:          store,
		SessionLifetime:       cfg.SessionLifetime,
		SessionCookiePersist:  cfg.SessionCookiePersist,
		SessionCookieSameSite: cfg.SessionCookieSameSite,
		SessionCookieSecure:   cfg.SessionCookieSecure,
		SessionCookieHTTPOnly: cfg.SessionCookieHTTPOnly,
		SessionCookiePath:     cfg.SessionCookiePath,
		TemplateFS:            templates.FS,
		TemplateFuncs:         funcs.NewFuncMap(),
		Stdout:                stdout,
		Stderr:                stderr,
	}


	// Initialize the app
	hopApp, err := hop.New(appConfig)
	if err != nil {
		return fmt.Errorf("error creating application: %w", err)
	}

	hopApp.SetSystemPagesLayout("minimal")
	
	// Set up the app
	// ===============
	a := app.New(app.Settings{
		App:        hopApp,
		Config:     cfg,
		DB:         d,
		Logger:     logger,
		Mailer:     mailer,
		Name:       AppName,
		Version:    AppVersion,
		BuildTime:  BuildTime,
		CommitHash: CommitHash,
	})
	

	// Start the server, blocking until it exits
	// ==============
	if err := a.Start(context.Background()); err != nil {
		return fmt.Errorf("error starting server: %w", err)
	}

}

Creating a Module

type MyModule struct{}

func New() *MyModule {
    return &MyModule{}
}

func (m *MyModule) ID() string {
    return "mymodule"
}

func (m *MyModule) Init() error {
    return nil
}

Documentation

Overview

Package hop provides an experimental, modular web application framework for Go.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type App

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

App represents the core application container that manages all framework components. It provides simple dependency injection, module management, and coordinates startup/shutdown of the application. App implements graceful shutdown and ensures modules are started and stopped in the correct order.

func New

func New(cfg AppConfig) (*App, error)

New creates a new application with core components

func (*App) Dispatcher

func (a *App) Dispatcher() *dispatch.Dispatcher

Dispatcher returns the event bus for the app

func (*App) Error

func (a *App) Error() error

Error returns the first error that occurred during initialization

func (*App) Flash

func (a *App) Flash() *flash.Manager

Flash returns the application's flash manager

func (*App) GetModule

func (a *App) GetModule(id string) (Module, error)

GetModule returns a module by ID

func (*App) Handler

func (a *App) Handler() http.Handler

Handler returns the http.Handler for the app

func (*App) Host

func (a *App) Host() string

Host returns the host address for the app

func (*App) Logger

func (a *App) Logger() *slog.Logger

Logger returns the logger instance for the app

func (*App) NewResponse

func (a *App) NewResponse(r *http.Request) *view.Response

NewResponse creates a new Response instance with the TemplateManager.

func (*App) NewTemplateData

func (a *App) NewTemplateData(r *http.Request) map[string]any

NewTemplateData returns a map of data that can be used in a Go template, API response, etc. It includes the current user, environment, version, and other useful information.

func (*App) OnShutdown

func (a *App) OnShutdown(fn func(context.Context) error)

OnShutdown registers a function to be called when the app is shutting down

func (*App) OnTemplateData

func (a *App) OnTemplateData(fn OnTemplateDataFunc)

OnTemplateData registers a function that populates template data each time a template is rendered.

func (*App) Port

func (a *App) Port() int

Port returns the port number for the app

func (*App) RegisterModule

func (a *App) RegisterModule(m Module) *App

RegisterModule adds a module to the app

func (*App) RunInBackground

func (a *App) RunInBackground(r *http.Request, fn func() error)

RunInBackground runs a function in the background via the server

func (*App) Session

func (a *App) Session() *scs.SessionManager

Session returns the session manager instance for the app

func (*App) SetSystemPagesLayout

func (a *App) SetSystemPagesLayout(name string)

SetSystemPagesLayout sets the template to use for rendering error pages

func (*App) ShutdownServer

func (a *App) ShutdownServer(ctx context.Context) error

ShutdownServer gracefully shuts down the server

func (*App) Start

func (a *App) Start(ctx context.Context) error

Start initializes the app and starts all modules and the server

func (*App) StartModules

func (a *App) StartModules(ctx context.Context) error

StartModules initializes and starts all modules without starting the server

func (*App) Stop

func (a *App) Stop(ctx context.Context) error

Stop gracefully shuts down the app and all modules. This is only called when the server is shutting down.

func (*App) TM

func (a *App) TM() *view.TemplateManager

TM returns the template manager instance for the app

type AppConfig

type AppConfig struct {
	// Environment is the application environment (default: "development")
	Environment string
	// Host is the host address to bind the server to (default: "" - all interfaces)
	Host string
	// Port is the port to bind the server to (default: 8080)
	Port int
	// Handler is the http.Handler to use for the server (default: http.DefaultServeMux)
	Handler http.Handler
	// IdleTimeout is the maximum amount of time to wait for the next request when keep-alives are enabled (default: 120s)
	IdleTimeout time.Duration
	// ReadTimeout is the maximum duration before timing out read of the request (default: 5s)
	ReadTimeout time.Duration
	// WriteTimeout is the maximum duration before timing out write of the response (default: 10s)
	WriteTimeout time.Duration
	// ShutdownTimeout is the maximum duration before timing out server shutdown (default: 10s)
	ShutdownTimeout time.Duration
	// Logger is the application's logging instance. If nil, a default logger will be created based on the configuration
	Logger *slog.Logger
	// TemplateFS is the file system to use for template files
	TemplateFS fs.FS
	// TemplateFuncs merges custom template functions into the default set of functions provided by hop. These are available in all templates.
	TemplateFuncs template.FuncMap
	// TemplateExt defines the extension for template files (default: ".html")
	TemplateExt string
	// SessionStore provides the storage backend for sessions
	SessionStore scs.Store
	// SessionCookieLifetime is the duration for session cookies to persist (default: 168h)
	SessionLifetime time.Duration
	// SessionCookiePersist determines whether session cookies persist after the browser is closed (default: true)
	SessionCookiePersist bool
	// SessionCookieSameSite defines the SameSite attribute for session cookies (default: "lax")
	SessionCookieSameSite string
	// SessionCookieSecure determines whether session cookies are for secure connections only (default: true)
	SessionCookieSecure bool
	// SessionCookieHTTPOnly determines whether session cookies are HTTP-only (default: true)
	SessionCookieHTTPOnly bool
	// SessionCookiePath is the path for session cookies (default: "/")
	SessionCookiePath string
	// Stdout writer for standard output (default: os.Stdout)
	Stdout io.Writer
	// Stderr writer for error output (default: os.Stderr)
	Stderr io.Writer
}

AppConfig provides configuration options for creating a new App instance. It allows customization of core framework components including logging, template rendering, session management, and I/O configuration.

type ConfigurableModule

type ConfigurableModule interface {
	Module
	// Configure applies the provided configuration to the module
	// The config parameter should be type asserted to the module's
	// specific configuration type
	Configure(ctx context.Context, config any) error
}

ConfigurableModule is implemented by modules that require configuration beyond basic initialization. The Configure method is called after Init but before Start.

type DispatcherModule

type DispatcherModule interface {
	Module
	// RegisterEvents registers the module's event handlers with the dispatcher
	RegisterEvents(events *dispatch.Dispatcher)
}

DispatcherModule is implemented by modules that handle application events. The RegisterEvents method is called after initialization to set up any event handlers the module provides.

type HTTPModule

type HTTPModule interface {
	Module
	// RegisterRoutes adds the module's routes to the provided router
	RegisterRoutes(handler http.Handler)
}

HTTPModule is implemented by modules that provide HTTP routes. The RegisterRoutes method is called after module initialization to set up any routes the module provides.

type Module

type Module interface {
	// ID returns a unique identifier for the module
	ID() string

	// Init performs any necessary module initialization
	// It is called when the module is registered with the application
	Init() error
}

Module is the base interface that all modules must implement. It provides identification and initialization capabilities for the module system.

type OnTemplateDataFunc

type OnTemplateDataFunc func(r *http.Request, data *map[string]any)

OnTemplateDataFunc is a function type that takes an HTTP request and a pointer to a map of data. It represents a callback function that can be used to populate data for templates.

type ShutdownModule

type ShutdownModule interface {
	Module
	// Stop performs cleanup actions for the module
	// It should respect the provided context's deadline for graceful shutdown
	Stop(ctx context.Context) error
}

ShutdownModule is implemented by modules that need to perform cleanup actions during application shutdown. Modules are shut down in reverse order of their startup.

type StartupModule

type StartupModule interface {
	Module
	// Start performs startup actions for the module
	// The provided context will be canceled when the application begins shutdown
	Start(ctx context.Context) error
}

StartupModule is implemented by modules that need to perform actions during application startup. The Start method will be called after all modules are initialized but before the HTTP server begins accepting connections.

type TemplateDataModule

type TemplateDataModule interface {
	Module
	// OnTemplateData allows the module to add data to the template context
	// The provided map will be merged with other template data
	OnTemplateData(r *http.Request, data *map[string]any)
}

TemplateDataModule is implemented by modules that provide data to templates. The OnTemplateData method is called for each template render to allow the module to add its data to the template context.

Directories

Path Synopsis
Package dispatch provides a lightweight, type-safe event bus implementation for building event-driven applications in Go.
Package dispatch provides a lightweight, type-safe event bus implementation for building event-driven applications in Go.
middleware
Package middleware provides HTTP middleware components for the route package.
Package middleware provides HTTP middleware components for the route package.
Package serve provides a way to create and manage an HTTP server, including routing, middleware, and graceful shutdown.
Package serve provides a way to create and manage an HTTP server, including routing, middleware, and graceful shutdown.

Jump to

Keyboard shortcuts

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