hyperview

package module
v0.0.5 Latest Latest
Warning

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

Go to latest
Published: Sep 4, 2024 License: Apache-2.0 Imports: 18 Imported by: 0

README

HyperView

Status: Experimental

HyperView is a Go package designed to simplify the process of rendering data into various output formats for web applications.

Overview

HyperView provides a fluent interface for building HTTP responses, primarily focusing on rendering data for HTML templates, JSON responses, and HTMX snippets. It uses an adapter-based architecture, allowing for flexible output formatting and easy extension to new formats.

Goals

  • Fluent API: Utilizes a builder pattern for constructing responses.
  • Multi-format Support: Renders output in HTML, JSON, HTMX, and other formats through adapters.
  • Template Integration: Works seamlessly with Go's html/template package.
  • Extensibility: Allows creation of custom adapters for additional output formats.
  • Performance: Designed with efficiency in mind for use in high-traffic applications.

Use Cases

HyperView could be useful for:

  • Web applications requiring multiple output formats (or just one, the fluent approach makes for a clean way to build responses)
  • APIs that need to serve both HTML and JSON responses
  • Projects using server-side rendering with occasional HTMX integration

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func JSONError

func JSONError(w http.ResponseWriter, message string, status int, headers ...http.Header) error

JSONError writes an error response in JSON format to the http.ResponseWriter. It takes the message and the status code of the error as input parameters. Optional headers can be provided to set additional response headers.

Example Usage: err := JSONError(w, "Internal Server Error", http.StatusInternalServerError, http.Header{})

Parameters: - w: The http.ResponseWriter to write the error response to. - message: The error message to be included in the response. - status: The HTTP status code of the error. - headers: Optional additional response headers.

Returns: - error: An error if JSONWithHeaders fails, otherwise nil.

func JSONFailure

func JSONFailure(w http.ResponseWriter, data any, message string, status int, headers ...http.Header) error

JSONFailure builds a JSON response with failure status, message and data. It uses the provided http.ResponseWriter to write the JSON response. The response code is set by the status parameter. The response headers can be passed as optional http.Header arguments.

func JSONRedirect

func JSONRedirect(w http.ResponseWriter, r *http.Request, url string, headers ...http.Header) error

JSONRedirect redirects the request to the specified URL and sends a JSON response.

func JSONSuccess

func JSONSuccess(w http.ResponseWriter, data any, headers ...http.Header) error

JSONSuccess creates a successful JSON response with the given data and optional headers. It uses the Envelope structure to encapsulate the data and set the response status, code, and message. It then calls the JSONWithHeaders function to format the JSON response with the specified headers. The function returns an error if there is an issue with formatting or writing the response to the writer.

func JSONSuccessWithStatus

func JSONSuccessWithStatus(w http.ResponseWriter, status int, data any, headers ...http.Header) error

JSONSuccessWithStatus creates a JSON response with the specified status code and data. It formats the response body as a success envelope and includes optional custom headers. It returns an error if writing the response fails.

func JSONWithHeaders

func JSONWithHeaders(w http.ResponseWriter, status int, data any, headers ...http.Header) error

JSONWithHeaders serializes the given data to JSON format with specified headers and writes it to the provided http.ResponseWriter. It also sets the HTTP status code and the Content-Type header to "application/json; charset=UTF-8". If the serialization fails, an error is returned. The function accepts optional headers that will be applied to the response.

Types

type Adapter

type Adapter interface {
	// Init initializes the view adapter.
	Init() error
	// Render renders the specified template with the provided data.
	Render(w http.ResponseWriter, r *http.Request, opts *response.Response)
	// RenderForbidden renders the forbidden page.
	RenderForbidden(w http.ResponseWriter, r *http.Request, opts *response.Response)
	// RenderMaintenance renders the maintenance page.
	RenderMaintenance(w http.ResponseWriter, r *http.Request, opts *response.Response)
	// RenderMethodNotAllowed renders the method not allowed page.
	RenderMethodNotAllowed(w http.ResponseWriter, r *http.Request, opts *response.Response)
	// RenderNotFound renders the not found page.
	RenderNotFound(w http.ResponseWriter, r *http.Request, opts *response.Response)
	// RenderSystemError renders the system error page.
	RenderSystemError(w http.ResponseWriter, r *http.Request, err error, opts *response.Response)
	// RenderUnauthorized renders the unauthorized page.
	RenderUnauthorized(w http.ResponseWriter, r *http.Request, opts *response.Response)
}

Adapter is an interface for rendering templates with various template engines.

type Envelope

type Envelope struct {
	Status  string `json:"status"`
	Message string `json:"message"`
	Data    any    `json:"data"`
	Code    int    `json:"code,omitempty"`
}

Envelope represents the structure of an envelope used for encapsulating response data.

type HyperView

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

HyperView provides a service to render views from different template adapters.

func NewHyperView

func NewHyperView(options ...Option) (*HyperView, error)

NewHyperView creates a new view service. It accepts a list of options to configure the view service.

Available options:

  • WithLayouts: sets the base and system layouts for the view service.
  • WithFuncMap: sets an initial function map to use for the template engine.
  • WithBaseTemplateFS: sets an initial template and assets filesystem to use for the template engine.
  • WithLogger: sets an initial logger to use for the HyperView instance. If not set, a default logger is created when the HyperView instance is created.
  • WithViewAdapter: sets a view adapter to use for the view service. If no view adapters are set, the default adapters are used. Default adapters use html/template for html templates and json for json templates.

func (*HyperView) Adapter

func (s *HyperView) Adapter(name string) (Adapter, bool)

Adapter returns the view adapter with the specified name

func (*HyperView) HxRedirect

func (s *HyperView) HxRedirect(w http.ResponseWriter, url string)

HxRedirect sends an HX-Redirect header to the client

func (*HyperView) Logger

func (s *HyperView) Logger() *slog.Logger

Logger provides access to the logger, so that plugins can use it.

func (*HyperView) MaybeRegisterDefaultAdapters

func (s *HyperView) MaybeRegisterDefaultAdapters() error

MaybeRegisterDefaultAdapters registers the built-in adapters for using html/template for html templates and json for json templates, but only if they are not already registered. The ext parameter is used to determine the file extension for the html template adapter.

func (*HyperView) NewResponse

func (s *HyperView) NewResponse(layout string) *response.Response

NewResponse creates a new response with the given layout

func (*HyperView) NewSystemResponse

func (s *HyperView) NewSystemResponse() *response.Response

NewSystemResponse creates a new response with the system layout

func (*HyperView) Redirect

func (s *HyperView) Redirect(w http.ResponseWriter, r *http.Request, url string)

Redirect sends a redirect response to the client

func (*HyperView) RegisterAdapter

func (s *HyperView) RegisterAdapter(name string, adapter Adapter) error

RegisterAdapter registers a new view adapter with the view service

func (*HyperView) Reinit

func (s *HyperView) Reinit() error

Reinit reinitialize the view service adapters. This is useful for reloading templates after they have changed.

func (*HyperView) Render

func (s *HyperView) Render(w http.ResponseWriter, r *http.Request, resp *response.Response)

Render renders the specified opts with the provided adapter key

func (*HyperView) RenderAs

func (s *HyperView) RenderAs(w http.ResponseWriter, r *http.Request, adapterKey string, resp *response.Response)

RenderAs renders the specified opts with the provided adapter key

func (*HyperView) RenderForbidden

func (s *HyperView) RenderForbidden(w http.ResponseWriter, r *http.Request)

RenderForbidden renders a forbidden page

func (*HyperView) RenderForbiddenAs

func (s *HyperView) RenderForbiddenAs(w http.ResponseWriter, r *http.Request, adapterKey string)

RenderForbiddenAs renders a forbidden page as the specified adapter

func (*HyperView) RenderMaintenance

func (s *HyperView) RenderMaintenance(w http.ResponseWriter, r *http.Request)

RenderMaintenance renders a maintenance page

func (*HyperView) RenderMaintenanceAs

func (s *HyperView) RenderMaintenanceAs(w http.ResponseWriter, r *http.Request, adapterKey string)

RenderMaintenanceAs renders a maintenance page as the specified adapter

func (*HyperView) RenderMethodNotAllowed

func (s *HyperView) RenderMethodNotAllowed(w http.ResponseWriter, r *http.Request)

RenderMethodNotAllowed renders a method not allowed page

func (*HyperView) RenderMethodNotAllowedAs

func (s *HyperView) RenderMethodNotAllowedAs(w http.ResponseWriter, r *http.Request, adapterKey string)

RenderMethodNotAllowedAs renders a method not allowed page as the specified adapter

func (*HyperView) RenderNotFound

func (s *HyperView) RenderNotFound(w http.ResponseWriter, r *http.Request)

RenderNotFound renders a 404 not found page

func (*HyperView) RenderNotFoundAs

func (s *HyperView) RenderNotFoundAs(w http.ResponseWriter, r *http.Request, adapterKey string)

RenderNotFoundAs renders a 404 not found page as the specified adapter

func (*HyperView) RenderSystemError

func (s *HyperView) RenderSystemError(w http.ResponseWriter, r *http.Request, err error)

RenderSystemError renders a system error page

func (*HyperView) RenderSystemErrorAs

func (s *HyperView) RenderSystemErrorAs(w http.ResponseWriter, r *http.Request, adapterKey string, err error)

RenderSystemErrorAs renders a system error page as the specified adapter

func (*HyperView) RenderUnauthorized

func (s *HyperView) RenderUnauthorized(w http.ResponseWriter, r *http.Request)

RenderUnauthorized renders an unauthorized page

func (*HyperView) RenderUnauthorizedAs

func (s *HyperView) RenderUnauthorizedAs(w http.ResponseWriter, r *http.Request, adapterKey string)

RenderUnauthorizedAs renders an unauthorized page as the specified adapter

type JSONAdapter

type JSONAdapter struct{}

JSONAdapter is an adapter for rendering JSON responses.

func NewJSONViewAdapter

func NewJSONViewAdapter() *JSONAdapter

NewJSONViewAdapter creates a new JSON view adapter.

func (*JSONAdapter) Init

func (v *JSONAdapter) Init() error

func (*JSONAdapter) Render

func (v *JSONAdapter) Render(w http.ResponseWriter, r *http.Request, resp *response.Response)

func (*JSONAdapter) RenderForbidden

func (v *JSONAdapter) RenderForbidden(w http.ResponseWriter, _ *http.Request, _ *response.Response)

func (*JSONAdapter) RenderMaintenance

func (v *JSONAdapter) RenderMaintenance(w http.ResponseWriter, _ *http.Request, _ *response.Response)

func (*JSONAdapter) RenderMethodNotAllowed

func (v *JSONAdapter) RenderMethodNotAllowed(w http.ResponseWriter, _ *http.Request, _ *response.Response)

func (*JSONAdapter) RenderNotFound

func (v *JSONAdapter) RenderNotFound(w http.ResponseWriter, _ *http.Request, _ *response.Response)

func (*JSONAdapter) RenderSystemError

func (v *JSONAdapter) RenderSystemError(w http.ResponseWriter, _ *http.Request, err error, _ *response.Response)

func (*JSONAdapter) RenderUnauthorized

func (v *JSONAdapter) RenderUnauthorized(w http.ResponseWriter, _ *http.Request, _ *response.Response)

type Option

type Option func(*HyperView) error

Option is a function that can be used to configure the HyperView struct.

func WithBaseTemplateFS

func WithBaseTemplateFS(efs *embed.FS) Option

WithBaseTemplateFS sets an initial template and assets filesystem to use for the template engine.

func WithFuncMap

func WithFuncMap(funcs template.FuncMap) Option

WithFuncMap sets an initial function map to use for the template engine. Additional functions can be added later via Plugin options.

func WithLayouts

func WithLayouts(base, system string) Option

WithLayouts sets the base and system layouts for the view service.

func WithLogger

func WithLogger(logger *slog.Logger) Option

WithLogger sets an initial logger to use for the HyperView instance. If not set, a default logger is created when the HyperView instance is created.

func WithViewAdapter

func WithViewAdapter(name string, adapter Adapter) Option

WithViewAdapter sets a view adapter to use for the view service. If no view adapters are set, the default adapters are used.

type TemplateAdapter

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

TemplateAdapter is a template adapter for the HyperView framework that uses the Go html/template package.

func NewTemplateViewAdapter

func NewTemplateViewAdapter(opts TemplateViewAdapterOptions) *TemplateAdapter

NewTemplateViewAdapter creates a new TemplateAdapter.

func (*TemplateAdapter) Init

func (a *TemplateAdapter) Init() error

func (*TemplateAdapter) Render

func (*TemplateAdapter) RenderForbidden

func (a *TemplateAdapter) RenderForbidden(w http.ResponseWriter, r *http.Request, resp *response.Response)

func (*TemplateAdapter) RenderMaintenance

func (a *TemplateAdapter) RenderMaintenance(w http.ResponseWriter, r *http.Request, resp *response.Response)

func (*TemplateAdapter) RenderMethodNotAllowed

func (a *TemplateAdapter) RenderMethodNotAllowed(w http.ResponseWriter, r *http.Request, resp *response.Response)

func (*TemplateAdapter) RenderNotFound

func (a *TemplateAdapter) RenderNotFound(w http.ResponseWriter, r *http.Request, resp *response.Response)

func (*TemplateAdapter) RenderSystemError

func (a *TemplateAdapter) RenderSystemError(w http.ResponseWriter, r *http.Request, err error, resp *response.Response)

func (*TemplateAdapter) RenderUnauthorized

func (a *TemplateAdapter) RenderUnauthorized(w http.ResponseWriter, r *http.Request, resp *response.Response)

type TemplateViewAdapterOptions

type TemplateViewAdapterOptions struct {
	// Extension is the file extension for the templates. Default is ".html".
	Extension string
	// FileSystemMap is a map of file systems to use for the templates.
	FileSystemMap map[string]fs.FS
	// Funcs is a map of functions to add to the template.FuncMap.
	Funcs template.FuncMap
	// Logger is the logger to use for the adapter.
	Logger *slog.Logger
}

TemplateViewAdapterOptions are the options for the TemplateAdapter.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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