waggy

package module
v0.8.0 Latest Latest
Warning

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

Go to latest
Published: Mar 17, 2023 License: BSD-3-Clause Imports: 13 Imported by: 0

README

Waggy

Go Reference Go Reportcard Codecov LICENSE

The dead simple, easy-to-use library for writing HTTP handlers and routers in Go that can be used in standard HTTP server environments or in WAGI (Web Assembly Gateway Interface) environments

What problems do Waggy solve?

With WAGI (Web Assembly Gateway Interface), HTTP requests are routed to specific handlers as defined in a modules.toml file (more information can be found here) to specific functions in a WASM module or WAT file. It accomplishes this by passing in the HTTP request information via os.Stdin and os.Args, and returning HTTP responses via os.Stdout. To remove considerable amounts of boilerplate code and to provide a familiar API for handling these WAGI HTTP requests, Waggy was created. It provides path parameter access functionality that will feel very reminiscent to those who have used gorilla/mux. Additionally, you can also map multiple handlers to a specific route based on the specific HTTP method that was used in the incoming request. Waggy also allows users to compile an entire server's worth of routes into a single WASM module and bypass setting up their routes via a modules.toml file if they so choose by handling mapping the route to the correct entry point (handler). But don't worry, you can also compile individual routes into their own WASM modules, too, so you can use the conventional modules.toml file for routing.


v0.5.0 improvements:
  • Restricting Methods: With v0.5.0, you have the ability to restrict HTTP methods on your handlers to make sure your endpoints are more secure

  • No Matched Routes: Another added feature in v0.5.0 is handling cases where no routes are matches to the route of the incoming request with generic 405 responses, as well as the ability to set custom handlers for the same edge case

How do I use Waggy?

Installing

To install Waggy in a repo, simply run

$ go get github.com/syke99/waggy

Then you can import the package in any go file you'd like

import "github.com/syke99/waggy"
Basic usage

Examples of using both Routers and Handlers for compiling WASM modules for WAGI can be found in the examples repo.

!!NOTE!!

To learn more about configuring, routing, compiling, and deploying WAGI routes, as well as the limitations of WAGI routes, please consult the WAGI docs and the TinyGo WASM docs

Who?

This library was developed by Quinn Millican (@syke99)

License

This repo is under the BSD 3 license, see LICENSE for details.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var AllHTTPMethods = func() string {
	return "ALL"
}

AllHTTPMethods allows you to easily set a handler all HTTP Methods

Functions

func ListenAndServe added in v0.6.0

func ListenAndServe[W WaggyEntryPoint](addr string, entryPoint W) error

ListenAndServe wraps a call to http.ListenAndServe and also uses a type constraint of WaggyEntryPoint so that only a *waggy.Router or *waggy.Handler can be used

func Serve added in v0.3.0

func Serve[W WaggyEntryPoint](entryPoint W) error

Serve wraps a call to cgi.serve and also uses a type constraint of WaggyEntryPoint so that only a *Router or *Handler can be used in the call to Serve and not accidentally allow calling a bare http.Handler

func ServeFile added in v0.4.11

func ServeFile(w http.ResponseWriter, contentType string, filePath string)

ServeFile is a convenience function for serving the file at the given filePath to the given http.ResponseWriter (w). If Waggy cannot find a file at the given path (if it doesn't exist or the volume was incorrectly mounted), this function will return a status 404. If any other error occurs, this function will return a 500. If no contentType is given, this function will set the Content-Type header to "application/octet-stream"

func Vars added in v0.3.0

func Vars(r *http.Request) map[string]string

Vars returns the values matching any path parameters if they exist, otherwise returns nil

func WriteDefaultErrorResponse added in v0.3.0

func WriteDefaultErrorResponse(w http.ResponseWriter, r *http.Request)

WriteDefaultErrorResponse returns the result of writing the set default error response inside the handler it is being used inside of. If no default error response has been set, this function will return an error.

func WriteDefaultResponse added in v0.3.0

func WriteDefaultResponse(w http.ResponseWriter, r *http.Request)

WriteDefaultResponse returns the result (number of bytes written and a nil value, or the error of that write) of writing the set default response inside the handler it is being used inside of. If no default response has been set, this function will return an error.

Types

type FullServer added in v0.5.2

type FullServer string

type Handler added in v0.5.3

type Handler struct {
	FullServer bool
	// contains filtered or unexported fields
}

Handler is used to handling various http.HandlerFuncs mapped by HTTP methods for an individual route

func NewHandler added in v0.8.0

func NewHandler(cgi *FullServer) *Handler

NewHandler initialized a new Handler and returns a pointer to it

func NewHandlerWithRoute added in v0.8.0

func NewHandlerWithRoute(route string, cgi *FullServer) *Handler

NewHandlerWithRoute initialized a new Handler with the provided route and returns a pointer to it. It is intended to be used whenever only compiling an individual *Handler instead of a full *Router

func (*Handler) Handler added in v0.5.6

func (wh *Handler) Handler(method string) http.HandlerFunc

func (*Handler) Logger added in v0.5.3

func (wh *Handler) Logger() *Logger

Logger returns the Handler's Logger. If no parent logger is inherited from a Router, or you provided a OverrideParentLogger whenever adding a Logger to the Handler, then the Handler's Logger will be returned. If no logger has been set, then this method will return nil

func (*Handler) Methods added in v0.5.3

func (wh *Handler) Methods() []string

Methods returns all HTTP methods that currently have a handler set

func (*Handler) Middleware added in v0.8.0

func (wh *Handler) Middleware() []middleware.MiddleWare

func (*Handler) RestrictMethods added in v0.5.3

func (wh *Handler) RestrictMethods(methods ...string) *Handler

RestrictMethods is a variadic function for restricting a handler from being able to be executed on the given methods

func (*Handler) Route added in v0.5.3

func (wh *Handler) Route() string

Route returns the route currently set for wh. It is a convenience function that greatly eases looping over Handlers and adding them to a Router

func (*Handler) ServeHTTP added in v0.5.3

func (wh *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP serves the route

func (*Handler) UpdateRoute added in v0.5.5

func (wh *Handler) UpdateRoute(route string)

UpdateRoute allows you to update the Handler's route

func (*Handler) Use added in v0.7.0

func (wh *Handler) Use(middleWare ...middleware.MiddleWare)

Use allows you to set inline Middleware http.Handlers for a specific *Handler

func (*Handler) WithDefaultErrorResponse added in v0.5.3

func (wh *Handler) WithDefaultErrorResponse(err WaggyError, statusCode int) *Handler

WithDefaultErrorResponse allows you to set a default error response for individual handlers

func (*Handler) WithDefaultLogger added in v0.5.3

func (wh *Handler) WithDefaultLogger() *Handler

WithDefaultLogger sets wh's logger to the default Logger

func (*Handler) WithDefaultResponse added in v0.5.3

func (wh *Handler) WithDefaultResponse(contentType string, body []byte) *Handler

WithDefaultResponse allows you to set a default response for individual handlers

func (*Handler) WithLogger added in v0.5.3

func (wh *Handler) WithLogger(logger *Logger, parentOverride ParentLoggerOverrider) *Handler

WithLogger allows you to set a logger for wh

func (*Handler) WithMethodHandler added in v0.6.0

func (wh *Handler) WithMethodHandler(method string, handler http.HandlerFunc) *Handler

WithMethodHandler allows you to map a different handler to each HTTP Method for a single route.

func (*Handler) WithRestrictedMethodHandler added in v0.5.3

func (wh *Handler) WithRestrictedMethodHandler(fn http.HandlerFunc) *Handler

WithRestrictedMethodHandler allows you to set an http.HandlerFunc to be used whenever a request with a restricted HTTP Method is hit. Whenever ServeHTTP is called, if this method has not been called and a restricted method has been set and is hit by the incoming request, it will return a generic 405 error, instead

type LogLevel added in v0.3.0

type LogLevel int

LogLevel allows you to set the level to be used in a *Logger

const (
	Info LogLevel = iota
	Debug
	Warning
	Fatal
	Error
	Warn
	All
	Off
)

type Logger added in v0.3.0

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

Logger is used for writing to a log

func Log added in v0.4.13

func Log(r *http.Request) *Logger

Log returns the *Logger for the current request handler to log a message to the set *os.File (defautls to os.Stderr) if one exists, otherwise nil

func NewLogger added in v0.3.0

func NewLogger(logLevel LogLevel, log *os.File) *Logger

NewLogger returns a new *Logger with the provided log file (if log is not nil) and the provided logLevel.

func (*Logger) Err added in v0.3.0

func (l *Logger) Err(err error) *Logger

Err provide an error to the *Logger to be logged

func (*Logger) Level added in v0.3.0

func (l *Logger) Level(level LogLevel) *Logger

Level update the level of a *Logger

func (*Logger) Msg added in v0.3.0

func (l *Logger) Msg(key string, msg string) (int, error)

Msg provide a message with a key to be logged and then logs the constructed log messed to the set *os.File (or default to os.Stderr)

func (*Logger) SetLogFile added in v0.3.0

func (l *Logger) SetLogFile(log *os.File) error

SetLogFile set a specific file for the logger to Write to. You must mount the volume that this file resides in whenever you configure your WAGI server via your modules.toml file for a *Logger to be able to write to the provided file

func (*Logger) Val added in v0.3.0

func (l *Logger) Val(key string, val any) *Logger

Val add a value with the corresponding key to be logged by the *Logger

type ParentLoggerOverrider added in v0.3.0

type ParentLoggerOverrider = func() bool

ParentLoggerOverrider overrides the parent *Logger in a Handler

func OverrideParentLogger added in v0.3.0

func OverrideParentLogger() ParentLoggerOverrider

OverrideParentLogger

type QueryParams added in v0.3.1

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

QueryParams contains a map containing all the query params from the provided *http.Request

func Query added in v0.3.1

func Query(r *http.Request) *QueryParams

Query returns QueryParams from the provided *http.Request

func (*QueryParams) Add added in v0.3.1

func (q *QueryParams) Add(key string, val string)

Add either appends the provided val at the provided key stored in q, or, if no value is currently stored at the provided key, then a new slice will be stored at the provided key and the provided val appended to it

func (*QueryParams) Del added in v0.3.1

func (q *QueryParams) Del(key string)

Del deletes the value(s) stored in q at the provided key

func (*QueryParams) Get added in v0.3.1

func (q *QueryParams) Get(key string) string

Get returns the first value stored in q with the provided key

func (*QueryParams) Set added in v0.3.1

func (q *QueryParams) Set(key string, val string)

Set sets the provided val in q with the provided key. If an existing value/set of values is already stored at the provided key, then Set will override that value

func (*QueryParams) Values added in v0.3.1

func (q *QueryParams) Values(key string) []string

Values returns a slice of all values stored in q with the provided key

type Router added in v0.5.3

type Router struct {
	FullServer bool
	// contains filtered or unexported fields
}

Router is used for routing incoming HTTP requests to specific *Handlers by the route provided whenever you call Handle on the return router and provide a route for the *Handler you provide

func NewRouter added in v0.8.0

func NewRouter(cgi *FullServer) *Router

NewRouter initializes a new Router and returns a pointer to it

func (*Router) Handle added in v0.5.3

func (wr *Router) Handle(route string, handler *Handler) *Router

Handle allows you to map a *Handler for a specific route. Just in the popular gorilla/mux router, you can specify path parameters by wrapping them with {} and they can later be accessed by calling Vars(r)

func (*Router) Logger added in v0.5.3

func (wr *Router) Logger() *Logger

Logger returns the Router's logger

func (*Router) Middleware added in v0.8.0

func (wr *Router) Middleware() []middleware.MiddleWare

func (*Router) Routes added in v0.5.6

func (wr *Router) Routes() []string

Routes returns all the routes that a *Router has *Handlers set for in the order that they were added

func (*Router) ServeHTTP added in v0.5.3

func (wr *Router) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP satisfies the http.Handler interface and calls the stored handler at the route of the incoming HTTP request

func (*Router) Use added in v0.7.0

func (wr *Router) Use(middleWare ...middleware.MiddleWare)

Use allows you to set Middleware http.Handlers for a *Router

func (*Router) Walk added in v0.6.0

func (wr *Router) Walk(walkFunc func(method string, route string) error) error

Walk accepts a *Router and a walkFunc to execute on each route that has been added to the *Router. It walks the *Router in the order that each *Handler was added to the *Router with *Router.Handle(). It returns the first error encountered

func (*Router) WithDefaultLogger added in v0.5.3

func (wr *Router) WithDefaultLogger() *Router

WithDefaultLogger sets wr's logger to the default Logger

func (*Router) WithLogger added in v0.5.3

func (wr *Router) WithLogger(logger *Logger) *Router

WithLogger allows you to set a Logger for the entire router. Whenever Handle is called, this logger will be passed to the *Handler being handled for the given route.

func (*Router) WithNoRouteHandler added in v0.5.3

func (wr *Router) WithNoRouteHandler(fn http.HandlerFunc) *Router

WithNoRouteHandler allows you to set an http.HandlerFunc to be used whenever no route is found. If this method is not called and the ServeHTTP method has been called, then it will return a generic 404 response, instead

type WaggyEntryPoint added in v0.3.0

type WaggyEntryPoint interface {
	*Router | *Handler
	ServeHTTP(w http.ResponseWriter, r *http.Request)
	Middleware() []middleware.MiddleWare
}

WaggyEntryPoint is used as a type constraint whenever calling Serve so that only a *Router or *Handler can be used and not a bare http.Handler

type WaggyError added in v0.3.0

type WaggyError struct {
	Type     string `json:"type"`
	Title    string `json:"title"`
	Detail   string `json:"detail"`
	Status   int    `json:"status"`
	Instance string `json:"instance"`
	Field    string `json:"field"`
}

WaggyError is provided to help simplify composing the body of an HTTP error response

Directories

Path Synopsis
internal

Jump to

Keyboard shortcuts

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