rio

package module
v0.0.12 Latest Latest
Warning

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

Go to latest
Published: May 24, 2024 License: MIT Imports: 15 Imported by: 0

README

Rio

rio logo

Rio is a zero-dependency web tookit for Go.


Key Features

🌐 Server - A thin wrapper around the http.ServeMux.

Handlers - A collection of useful http handlers.

🔗 Middleware - A collection of useful middleware handlers.

💬 Responses - Quick helpers for http/json responses.

🎨 Template Rendering - Helpful utilities for HTML template rendering.

📝 Logger - Simple, easy to use logger.

Validator - Validates data.


Illustration by @sjbitcode! ✨

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func BasicHttp

func BasicHttp(msg string) http.Handler

BasicHttp is an http handler which serves a custom message with a status of 200 OK.

mux.Handle("/", BasicHttp("hi"))

.

func BasicJson

func BasicJson(msg string) http.Handler

BasicJson is an http handler which serves a custom json message with a status of 200 OK.

mux.Handle("/", BasicJson("hi"))

.

func CacheControl

func CacheControl(next http.Handler) http.Handler

CacheControl is a middleware which sets the caching policy for assets. Defaults to 2 days.

func CacheControlWithAge

func CacheControlWithAge(age int) func(http.Handler) http.Handler

CacheControlWithAge is a middleware which sets the caching policy for assets.

func FileServer

func FileServer(fsys fs.FS) http.Handler

FileServer is an http handler which serves files from the given file system.

mux.Handle("/static/", FileServer(fsys))

.

func FileServerDir

func FileServerDir(root, prefix string) http.Handler

FileServerDir is an http handler which serves files from the file system. Root is the filesystem root. Prefix is the prefix of the request path to strip off before searching the filesystem for the given file.

mux.Handle("/static/", FileServerDir("./staticfiles", "/static/"))

.

func Http200

func Http200(w http.ResponseWriter, msg string)

func Http301

func Http301(w http.ResponseWriter, msg string)

func Http400

func Http400(w http.ResponseWriter, msg string)

func Http401

func Http401(w http.ResponseWriter, msg string)

func Http403

func Http403(w http.ResponseWriter, msg string)

func Http404

func Http404(w http.ResponseWriter, msg string)

func Http500

func Http500(w http.ResponseWriter)

func Json200

func Json200(w http.ResponseWriter, data any) error

func Json201

func Json201(w http.ResponseWriter, data any) error

func Json204

func Json204(w http.ResponseWriter, data any) error

func Json301

func Json301(w http.ResponseWriter, data any) error

func Json400

func Json400(w http.ResponseWriter, data any) error

func Json401

func Json401(w http.ResponseWriter, data any) error

func Json403

func Json403(w http.ResponseWriter, data any) error

func Json404

func Json404(w http.ResponseWriter, data any) error

func Json500

func Json500(w http.ResponseWriter) error

func LogDebug

func LogDebug(msg string, attrs ...slog.Attr)

LogDebug logs a debug message.

func LogError

func LogError(err error, attrs ...slog.Attr)

LogError logs an error.

func LogInfo

func LogInfo(msg string, attrs ...slog.Attr)

LogInfo logs an info message.

func LogRequest

func LogRequest(next http.Handler) http.Handler

Logger is a middleware which logs the http request and response status.

func LogWarn

func LogWarn(msg string, attrs ...slog.Attr)

LogWarn logs a warning message.

func Logger

func Logger(l *slog.Logger)

Logger sets the default logger to the given slog.Logger.

func MakeHandler

func MakeHandler(next HandlerFunc) http.Handler

MakeHandler is a middleware which converts a rio.HandlerFunc to an http.Handler. It centralizes the error handling with the custom AppError error type.

func NewLogger

func NewLogger(w io.Writer) *slog.Logger

NewLogger constructs and returns a new *slog.Logger.

func NotFound

func NotFound(next http.Handler) http.Handler

NotFound is a middleware which returns a 404 Not Found error if the request path is not "/".

func NotFoundJson

func NotFoundJson(next http.Handler) http.Handler

NotFound is a middleware which returns a 404 Not Found json error if the request path is not "/".

func RecoverPanic

func RecoverPanic(next http.Handler) http.Handler

RecoverPanic is a middleware which recovers from panics and logs a HTTP 500 (Internal Server Error) if possible.

func Render

func Render(w http.ResponseWriter, page string, status int, data any) error

Render writes a template to the http.ResponseWriter.

func SecureHeaders

func SecureHeaders(next http.Handler) http.Handler

SecureHeaders is a middleware which adds HTTP security headers to every response, inline with current OWASP guidance.

func Serve

func Serve(addr string, handler http.Handler) error

Serve starts an http server.

The addr is the address to listen to. The addr assumes the format "host:port". The handler is the http.Handler to serve.

func Templates

func Templates(templatesFS fs.FS, opts ...ViewOpt)

Templates configures the default view with the given templateFS filesystem and the opts functional options.

func WrapItem added in v0.0.3

func WrapItem[T any](val T) func() T

WrapItem wraps a value of any type in a func. This is used to inject values into the template.FuncMap.

func WrapMap added in v0.0.7

func WrapMap[T any](val map[string]T) func() map[string]T

WrapMap wraps a map of type [string]any in a func. This is used to inject values into the template.FuncMap.

func WrapSlice added in v0.0.7

func WrapSlice[T any](val []T) func() []T

WrapSlice wraps a slice of any type in a func. This is used to inject values into the template.FuncMap.

Types

type AppError

type AppError struct {
	Message string
	Status  int
	IsJson  bool
}

AppError is custom error type for Http/Json errors.

func HttpError

func HttpError(message string, status int) AppError

HttpError constructs and returns an Http AppError.

func JsonError

func JsonError(message string, status int) AppError

JsonError constructs and returns a Json AppError.

func (AppError) Error

func (a AppError) Error() string

Error satisfies the error interface.

func (AppError) WriteTo

func (a AppError) WriteTo(w http.ResponseWriter) error

WriteTo writes the AppError to the given ResponseWriter.

If the AppError is Json, then a json object containing the message will be written. If the AppError is not Json, then a plain text message will be written.

type HandlerFunc

type HandlerFunc func(http.ResponseWriter, *http.Request) error

HandlerFunc is a custom http handler signature which accepts an http.ResponseWriter, *http.Request and returns an error. HandlerFuncs must be converted into an http.Handler with the MakeHandler middleware.

type Server

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

Server is a wrapper around the standard http.ServeMux.

It can register routes for Handlers and HandlerFuncs. It can also register middleware for the entire ServeMux.

func NewServer

func NewServer() *Server

NewServer constructs and returns a new *Server.

The underlying mux is the standard http.ServeMux. The LogRequest, RecoverPanic and SecureHeaders middleware are automatically registered on construction.

func (*Server) Handle

func (s *Server) Handle(pattern string, handler http.Handler)

Handler registers the handler for the given pattern. It is a proxy for http.ServeMux.Handle().

func (*Server) HandleFunc

func (s *Server) HandleFunc(pattern string, handler func(http.ResponseWriter, *http.Request))

HandleFunc registers the handler function for the given pattern. It is a proxy for http.ServeMux.HandleFunc().

func (*Server) Handler

func (s *Server) Handler() http.Handler

Handler returns the Server as an http.Handler.

It wraps the ServeMux with the middleware handlers, and returns the result as an http.Handler.

The middleware is reversed, so that the earliest registered middleware is wrapped last.

func (*Server) Serve

func (s *Server) Serve(addr string) error

Serve starts an http server on the given address.

func (*Server) Use

func (s *Server) Use(middleware ...func(http.Handler) http.Handler)

Use registers one or more handlers as middleware for the Server.

type View

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

View is a collection of html templates for rendering.

func NewView

func NewView(templatesFS fs.FS, opts ...ViewOpt) *View

NewView constructs and returns a new *View.

The templateFS is a filesystem which contains html templates. The opts is a slice of ViewOpt funcs for optional configuration.

func (*View) Render

func (v *View) Render(w http.ResponseWriter, page string, status int, data any) error

Render writes a template to the http.ResponseWriter.

type ViewOpt

type ViewOpt func(*View)

ViewOpt is a function to configure a View.

func WithFuncMap

func WithFuncMap(funcMap template.FuncMap) ViewOpt

WithFuncMap adds the functions in the given funcMap to the View.

If the View contains a funcMap function with the same name, then it will not be added.

Directories

Path Synopsis
Package format implements functions to format numbers, dates, times and strings.
Package format implements functions to format numbers, dates, times and strings.
Package forms implements utilities to parse and validate data.
Package forms implements utilities to parse and validate data.
internal

Jump to

Keyboard shortcuts

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