reply

package module
v0.5.0 Latest Latest
Warning

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

Go to latest
Published: Feb 29, 2024 License: MIT Imports: 7 Imported by: 0

README

reply

GoDoc tests Go Report Card

reply is a Go HTTP response engine. It provides convenience methods for common HTTP responses.

Installation
go get github.com/novrin/reply

Usage

In the example below, we add a reply engine to a application and use it in its HTTP handlers to compose replies to requests.

package main

import (
	"fmt"
	"net/http"

	"github.com/novrin/reply/internal/database" 
	"github.com/novrin/reply"
)

// Application orchestrates replies to server requests.
type Application struct {
	db    *database.Queries
	reply reply.Engine // Use a reply Engine to write responses 
}

// Home renders the home template.
func (app *Application) Home(w http.ResponseWriter, r *http.Request) {
	if r.URL.Path != "/" {
		app.reply.NotFound(w)
		return
	}
	users, err := app.db.Users(r.Context())
	if err != nil {
		app.reply.InternalServerError(w, fmt.Errorf("failed to retrieve users: %s", err.Error()))
		return
	}
	app.reply.OK(w, reply.Options{
		Key:  "home.html",
		Name: "base",
		Data: struct{ Users []database.Users }{Users: users},
	})
}

License

MIT

Copyright (c) 2023-present novrin

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func TemplateMap

func TemplateMap(fsys fs.FS, src string, base string, funcs template.FuncMap) (map[string]*template.Template, error)

TemplateMap returns a map of string to HTML template using fsys as its source.

Types

type Engine

type Engine struct {
	// Debug defines whether error strings encountered in the Writer's Reply
	// are sent in responses. If debug is false, the error string will simply
	// be the plain text representation of the error code.
	Debug bool

	// Writer is an interface used to construct replies to HTTP server requests.
	Writer
}

Engine provides convenience reply methods by wrapping its embedded Writer's Error and Reply.

func (Engine) BadGateway added in v0.5.0

func (e Engine) BadGateway(w http.ResponseWriter)

BadGateway replies with HTTP Status 502 Bad Gateway.

func (Engine) BadRequest

func (e Engine) BadRequest(w http.ResponseWriter)

BadRequest replies with HTTP Status 400 Bad Request.

func (Engine) Conflict added in v0.4.0

func (e Engine) Conflict(w http.ResponseWriter)

Conflict replies with HTTP Status 409 Conflict.

func (Engine) Created

func (e Engine) Created(w http.ResponseWriter, opts Options)

Created replies with HTTP 201 Status Created.

func (Engine) ExpectationFailed added in v0.5.0

func (e Engine) ExpectationFailed(w http.ResponseWriter)

ExpectationFailed replies with HTTP Status 417 Expectation Failed.

func (Engine) FailedDependency added in v0.5.0

func (e Engine) FailedDependency(w http.ResponseWriter)

FailedDependency replies with HTTP Status 424 Failed Dependency.

func (Engine) Forbidden

func (e Engine) Forbidden(w http.ResponseWriter)

Forbidden replies with HTTP Status 403 Forbidden.

func (Engine) GatewayTimeout added in v0.5.0

func (e Engine) GatewayTimeout(w http.ResponseWriter)

GatewayTimeout replies with HTTP Status 504 Gateway Timeout.

func (Engine) Gone added in v0.4.0

func (e Engine) Gone(w http.ResponseWriter)

Gone replies with HTTP Status 410 Gone.

func (Engine) HTTPVersionNotSupported added in v0.5.0

func (e Engine) HTTPVersionNotSupported(w http.ResponseWriter)

HTTPVersionNotSupported replies with HTTP Status 505 HTTP Version Not Supported.

func (Engine) InsufficientStorage added in v0.5.0

func (e Engine) InsufficientStorage(w http.ResponseWriter)

InsufficientStorage replies with HTTP Status 507 Insufficient Storage.

func (Engine) InternalServerError

func (e Engine) InternalServerError(w http.ResponseWriter)

InternalServerError replies with HTTP Status 500 Internal Server Error.

func (Engine) LengthRequired added in v0.5.0

func (e Engine) LengthRequired(w http.ResponseWriter)

LengthRequired replies with HTTP Status 411 Length Required.

func (Engine) Locked added in v0.5.0

func (e Engine) Locked(w http.ResponseWriter)

Locked replies with HTTP Status 423 Locked.

func (Engine) LoopDetected added in v0.5.0

func (e Engine) LoopDetected(w http.ResponseWriter)

LoopDetected replies with HTTP Status 508 Loop Detected.

func (Engine) MethodNotAllowed

func (e Engine) MethodNotAllowed(w http.ResponseWriter)

MethodNotAllowed replies with HTTP Status 405 Method Not Allowed.

func (Engine) MisdirectedRequest added in v0.5.0

func (e Engine) MisdirectedRequest(w http.ResponseWriter)

MisdirectedRequest replies with HTTP Status 421 Misdirected Request.

func (Engine) NetworkAuthenticationRequired added in v0.5.0

func (e Engine) NetworkAuthenticationRequired(w http.ResponseWriter)

NetworkAuthenticationRequired replies with HTTP Status 511 Network Authentication Required

func (Engine) NoContent

func (e Engine) NoContent(w http.ResponseWriter)

NoContent replies with HTTP Status 204 No Content.

func (Engine) NotAcceptable added in v0.4.0

func (e Engine) NotAcceptable(w http.ResponseWriter)

NotAcceptable replies with HTTP Status 406 Not Acceptable.

func (Engine) NotFound

func (e Engine) NotFound(w http.ResponseWriter)

NotFound replies with HTTP Status 404 Not Found.

func (Engine) NotImplemented added in v0.5.0

func (e Engine) NotImplemented(w http.ResponseWriter)

NotImplemented replies with HTTP Status 501 Not Implemented.

func (Engine) OK

func (e Engine) OK(w http.ResponseWriter, opts Options)

OK replies with HTTP 200 Status OK.

func (Engine) PreconditionFailed added in v0.5.0

func (e Engine) PreconditionFailed(w http.ResponseWriter)

PreconditionFailed replies with HTTP Status 412 Precondition Failed.

func (Engine) PreconditionRequired added in v0.5.0

func (e Engine) PreconditionRequired(w http.ResponseWriter)

PreconditionRequired replies with HTTP Status 428 Precondition Required.

func (Engine) ProxyAuthRequired added in v0.5.0

func (e Engine) ProxyAuthRequired(w http.ResponseWriter)

ProxyAuthRequired replies with HTTP Status 407 Proxy Authentication Required.

func (Engine) ReplyOrError added in v0.4.0

func (e Engine) ReplyOrError(w http.ResponseWriter, code int, opts Options)

ReplyOrError wraps Reply with error debugging. If an error is encountered in Reply, the Writer's Error function is triggered. Error essages are replaced with 'Internal Server Error' if e.Debug is false.

func (Engine) RequestEntityTooLarge added in v0.5.0

func (e Engine) RequestEntityTooLarge(w http.ResponseWriter)

RequestEntityTooLarge replies with HTTP Status 413 Request Entity Too Large.

func (Engine) RequestHeaderFieldsTooLarge added in v0.5.0

func (e Engine) RequestHeaderFieldsTooLarge(w http.ResponseWriter)

RequestHeaderFieldsTooLarge replies with HTTP Status 431 Request Header Fields Too Large.

func (Engine) RequestTimeout added in v0.4.0

func (e Engine) RequestTimeout(w http.ResponseWriter)

RequestTimeout replies with HTTP Status 408 Request Timeout.

func (Engine) RequestURITooLong added in v0.5.0

func (e Engine) RequestURITooLong(w http.ResponseWriter)

RequestURITooLong replies with HTTP Status 414 Request URI Too Long.

func (Engine) RequestedRangeNotSatisfiable added in v0.5.0

func (e Engine) RequestedRangeNotSatisfiable(w http.ResponseWriter)

RequestedRangeNotSatisfiable replies with HTTP Status 416 Requested Range Not Satisfiable.

func (Engine) ServiceUnavailable added in v0.5.0

func (e Engine) ServiceUnavailable(w http.ResponseWriter)

ServiceUnavailable replies with HTTP Status 503 Service Unavailable.

func (Engine) Teapot added in v0.5.0

func (e Engine) Teapot(w http.ResponseWriter)

Teapot replies with HTTP Status 418 I'm a teapot.

func (Engine) TooEarly added in v0.5.0

func (e Engine) TooEarly(w http.ResponseWriter)

TooEarly replies with HTTP Status 425 Too Early.

func (Engine) TooManyRequests added in v0.4.0

func (e Engine) TooManyRequests(w http.ResponseWriter)

TooManyRequests replies with HTTP Status 429 Too Many Requests.

func (Engine) Unauthorized

func (e Engine) Unauthorized(w http.ResponseWriter)

Unauthorized replies with HTTP Status 401 Unauthorized.

func (Engine) UnavailableForLegalReasons added in v0.5.0

func (e Engine) UnavailableForLegalReasons(w http.ResponseWriter)

UnavailableForLegalReasons replies with HTTP Status 451 Unavailable For Legal Reasons.

func (Engine) UnprocessableEntity added in v0.4.0

func (e Engine) UnprocessableEntity(w http.ResponseWriter)

UnprocessableEntity replies with HTTP Status 422 Unprocessable Entity.

func (Engine) UnsupportedMediaType added in v0.5.0

func (e Engine) UnsupportedMediaType(w http.ResponseWriter)

UnsupportedMediaType replies with HTTP Status 415 Unsupported Media Type.

func (Engine) UpgradeRequired added in v0.5.0

func (e Engine) UpgradeRequired(w http.ResponseWriter)

UpgradeRequired replies with HTTP Status 426 Upgrade Required.

func (Engine) VariantAlsoNegotiates added in v0.5.0

func (e Engine) VariantAlsoNegotiates(w http.ResponseWriter)

VariantAlsoNegotiates replies with HTTP Status 506 Variant Also Negotiates.

type JSONWriter added in v0.2.0

type JSONWriter struct{}

JSONWriter implements Writer for JSON responses.

func (JSONWriter) Error added in v0.2.0

func (jw JSONWriter) Error(w http.ResponseWriter, error string, code int)

Error sends an HTTP response header with the given status code and writes an encoded JSON error to w.

func (JSONWriter) Reply added in v0.3.0

func (jw JSONWriter) Reply(w http.ResponseWriter, code int, opts Options) error

Reply sends an HTTP status response header with the given status code and writes encoded JSON to w using the opts provided. If an error occurs at encoding, the function exits and does not write to w.

type Options

type Options struct {
	// TemplateKey defines a lookup in an TemplateWriter's Templates.
	// This is always required for a TemplateWriter; if not supplied,
	// its Reply will write an Internal Server Error.
	TemplateKey string

	// TemplateName defines an optional named template to execute.
	// This optional even for a TemplateWriter.
	TemplateName string

	// Data defines data for use in a reply.
	Data any
}

Options represents fields used in Reply.

type TemplateWriter

type TemplateWriter struct {
	Templates map[string]*template.Template
}

Template writer implements Writer for template responses.

func NewTemplateWriter added in v0.3.0

func NewTemplateWriter(templates map[string]*template.Template) *TemplateWriter

NewTemplateWriter returns a new TemplateWriter with the given templates and an empty buffer. If no "error.html" or "no_content.html" are supplied in templates, defaults are parsed and used.

func (*TemplateWriter) Error

func (tw *TemplateWriter) Error(w http.ResponseWriter, error string, code int)

Error sends an HTTP response header with the given status code and writes tw's executed "error.html" template to w. It does not otherwise end the request; the caller should ensure no further writes are done to w.

func (*TemplateWriter) Reply added in v0.3.0

func (tw *TemplateWriter) Reply(w http.ResponseWriter, code int, opts Options) error

Reply sends an HTTP status response header with the given status code and writes an executed template to w using the opts provided. If an error occurs at template execution, the function exits and does not write to w.

type Writer

type Writer interface {
	Error(w http.ResponseWriter, error string, code int)
	Reply(w http.ResponseWriter, code int, opts Options) error
}

Writer is used by an Engine to construct replies to HTTP server requests.

Jump to

Keyboard shortcuts

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