raggett

package module
v0.1.9 Latest Latest
Warning

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

Go to latest
Published: Apr 14, 2022 License: MIT Imports: 22 Imported by: 0

README

Raggett

codecov Test CodeQL

Raggett is an opinionated Go HTTP Server Framework

Installing

go get github.com/heyvito/raggett@v0.1.7

Usage

Raggett is built on top of Chi to provide routing and middlewares; the way it handles requests and responses are the main difference between the common way Go HTTP servers are built. Instead of implementing handlers dealing with both http.Request and http.ResponseWriter, the library encapsulates all common operations on a single Request object. The library also makes heavy usage of Zap to provide logging facilities.

The following snippet represents a simple Raggett Application:

package main

import (
    "fmt"
    "net/http"

    "github.com/heyvito/raggett"
    "go.uber.org/zap"
)

type HelloRequest struct {
    *raggett.Request
    Name string `form:"name" required:"true" blank:"false"`
}

func main() {
    mux := raggett.NewMux(zap.L())

    // Handlers must be a function accepting a single struct that uses
    // *raggett.Request as a promoted field, and returns an error.
    mux.Post("/", func(r HelloRequest) error {
        r.RespondString(fmt.Sprintf("Hello, %s!", r.Name))
        return nil
    })

    http.ListenAndServe(":3000", mux)
}

The same application can also be extended to provide both HTML and plain text responses by implementing a structure implementing a set of interfaces provided by the library. For instance:

package main

import (
    "fmt"
    "net/http"

    "github.com/heyvito/raggett"
    "go.uber.org/zap"
)

type HelloRequest struct {
    *raggett.Request
    Name string `form:"name" required:"true" blank:"false"`
}

type HelloResponse struct {
    Name string
}

func (h HelloResponse) JSON() interface{} {
    return map[string]interface{}{
        "greeting": fmt.Sprintf("Hello, %s!", h.Name),
    }
}

func (h HelloResponse) HTML() string {
    return fmt.Sprintf("<h1>Hello, %s!</h1>", h.Name)
}

func main() {
    mux := raggett.NewMux(zap.L())
    mux.Post("/", func(r HelloRequest) error {
        r.Respond(HelloResponse{
            Name: r.Name,
        })
        return nil
    })

    http.ListenAndServe(":3000", mux)
}

Accessing Form Values

When defining a request object, form values can be automatically loaded and converted to specific types by using tags:

type SignUpRequest struct {
    *raggett.Request
    Name                string `form:"name" required:"true" blank:"false"`
    Email               string `form:"email" pattern:"^.+@.+\..+$"`
    SubscribeNewsletter bool   `form:"subscribe"`
}

Accessing QueryString Values

The same pattern used by forms can be applied to QueryString parameters:

type ListUsersRequest struct {
    *raggett.Request
    Page int `query:"page"`
}

Accessing URL Parameters

As Raggett is built on top of Chi, URL parameters can also be accessed through fields defined on structs and marked with tags:

type ListPostsForDay struct {
    *raggett.Request
    Day   int `url-param:"day"`
    Month int `url-param:"month"`
    Year  int `url-param:"year"`
}

mux.Get("/blog/posts/{day}/{month}/{year}", func(r ListPostsForDay) error {
        // ...
    })

Parsing Request Bodies

When not using Forms or Multipart requests, applications can also rely on JSON or XML being posted, for instance. For that, Raggett has a set of Resolvers that can be attached directly to a field indicating that the request's body must be parsed and set it:

type SignUpRequest struct {
    *raggett.Request
    UserData struct {
        Email string `json:"email"`
        Name  string `json:"name"`
    } `body:"json"`
}

Receiving Files

Multipart data is also supported. To receive a single file:

type ExampleRequest struct {
    *raggett.Request
    Photo *raggett.FileHeader `form:"photo" required:"false"`
}

Or multiple files:

type ExampleRequest struct {
    *raggett.Request
    Photos []*raggett.FileHeader `form:"photo" required:"false"`
}

ProTip™: raggett.FileHeader is simply an alias to stdlib's multipart.FileHeader. Both types are interchangeable on Raggett.

Accessing Headers

Just like other values, headers can also be obtained through tags:

type AuthenticatedRequest struct {
    *raggett.Request
    Authorization string `header:"authorization" required:"true"`
}

Defaults

Raggett provides default handlers for errors such as validation (HTTP 400), runtime (HTTP 500), Not Found (HTTP 404), and Method Not Allowed (HTTP 405). For those errors, the library is capable of responding to the following formats, based on the Accept header provided by the client:

  • HTML
  • JSON
  • XML
  • Plain Text

The library also provides a "Development" mode, which augments information provided by those error handlers:

mux := raggett.NewMux(...)
mux.Development = true

⚠ Warning! Setting Development to true on production environments is unadvised, since it may cause sensitive information to be exposed to the internet.

License

The MIT License (MIT)

Copyright (c) 2022 Victor Gama de Oliveira

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

Documentation

Overview

Code generated by generators/generate_errors.go. DO NOT EDIT. This file was generated by a tool. Modifications will be overwritten.

Index

Constants

View Source
const (
	FileFieldKindNone fileFieldKind = 1 << iota
	FileFieldKindStdLib
	FileFieldKindRaggettLib
	FileFieldKindSlice
)

Variables

View Source
var ErrIncorrectArgType = fmt.Errorf("invalid argument type. Must be a struct using a *raggett.Request promoted structField")
View Source
var ErrIncorrectArgsArity = fmt.Errorf("invalid arguments arity. Expected 1")
View Source
var ErrIncorrectOutArity = fmt.Errorf("invalid returns arity. Expected 1")
View Source
var ErrNoFunction = fmt.Errorf("handler must be a function")

Functions

This section is empty.

Types

type BytesResponder

type BytesResponder interface {
	Bytes() []byte
}

type ChainedCookie added in v0.1.9

type ChainedCookie struct {
	// contains filtered or unexported fields
}
func Cookie(name, value string) *ChainedCookie

Cookie creates a new basic cookie with the provided name and value. The returned value can be use chained methods from ChainedCookie in order to set other cookie parameters. See ChainedCookie's documentation for further information. The result of this method (and chaining) can be provided directly to your request object. For instance:

 func HandleSomething(req MyRequestObject) error {
		req.AddCookie(raggett.Cookie("name", "value").HTTPOnly().Secure())
     // ...
 }

func (*ChainedCookie) Domain added in v0.1.9

func (c *ChainedCookie) Domain(domain string) *ChainedCookie

Domain sets the cookie's domain component. See more: https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies#define_where_cookies_are_sent

func (*ChainedCookie) ExpiresIn added in v0.1.9

func (c *ChainedCookie) ExpiresIn(duration time.Duration) *ChainedCookie

ExpiresIn sets the lifetime duration for this cookie. For instance, for a cookie to automatically expire in a day, use 24 * time.Hour See More: https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies#define_the_lifetime_of_a_cookie

func (*ChainedCookie) ExpiresNow added in v0.1.9

func (c *ChainedCookie) ExpiresNow() *ChainedCookie

ExpiresNow is a convenience method that marks this cookie as already expired. This can be used to immediately "delete" a cookie from the browser.

func (*ChainedCookie) HTTPOnly added in v0.1.9

func (c *ChainedCookie) HTTPOnly() *ChainedCookie

HTTPOnly sets the cookie as HTTPOnly, rendering it inaccessible to the JavaScript Document.cookie API; it's only sent to the server. For example, cookies that persist in server-side sessions don't need to be available to JavaScript and should have the HttpOnly attribute. This precaution helps mitigate cross-site scripting (XSS) attacks.

func (*ChainedCookie) Path added in v0.1.9

func (c *ChainedCookie) Path(path string) *ChainedCookie

Path sets the cookie's path component. See more: https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies#define_where_cookies_are_sent

func (*ChainedCookie) SameSite added in v0.1.9

func (c *ChainedCookie) SameSite(sameSite http.SameSite) *ChainedCookie

SameSite declares whether the cookie should be restricted to a first-party or same-site context. See more: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie/SameSite

func (*ChainedCookie) Secure added in v0.1.9

func (c *ChainedCookie) Secure() *ChainedCookie

Secure marks the cookie with the Secure flag. A cookie with the Secure attribute is only sent to the server with an encrypted request over the HTTPS protocol. It's never sent with unsecured HTTP (except on localhost), which means man-in-the-middle attackers can't access it easily. Insecure sites (with http: in the URL) can't set cookies with the Secure attribute.

type CustomRequestParser

type CustomRequestParser interface {
	ParseRequest(r *Request) error
}

CustomRequestParser implements a ParseRequest that will be invoked with a request before the handler is invoked. Returning an error from this function prevents the handler from being invoked.

type CustomResponder

type CustomResponder interface {
	RespondsToMediaTypes() []MediaType
	HandleMediaTypeResponse(mt MediaType, w io.Writer) error
}

type EmptyRequest

type EmptyRequest struct {
	*Request
}

EmptyRequest is a convenience type for a struct containing only a *Request field.

type ErrBodyFormsConflict

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

ErrBodyFormsConflict indicates that a given structure has fields using mixed `body:"*"` and `form:"*"` tags. As forms are parsed from the request's body, mixing both may lead to unexpected results, and therefore is not allowed.

func (ErrBodyFormsConflict) Error

func (e ErrBodyFormsConflict) Error() string

type ErrCustomRequestParserConflict

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

ErrCustomRequestParserConflict indicates that a given structure has a ParseRequest method implemented, which makes it implement CustomRequestParser. Implementing this interface makes the implementing structure ineligible to use fields with tags `form:"*"` or `body:"*"`.

func (ErrCustomRequestParserConflict) Error

type ErrEmptyBodyTag

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

ErrEmptyBodyTag indicates that a given structure has a body field without a value. Either provide a valid body format (such as `json`, `xml`, `text`, `stream`, or `bytes`), or consider implementing CustomRequestParser.

func (ErrEmptyBodyTag) Error

func (e ErrEmptyBodyTag) Error() string

type ErrEmptyPattern

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

ErrEmptyPattern indicates that a given structure contains a field using a `pattern` tag with an empty value.

func (ErrEmptyPattern) Error

func (e ErrEmptyPattern) Error() string

type ErrFieldsWithoutResolver

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

ErrFieldsWithoutResolver indicates that a given structure has inconsistent fields using one or more validator tags without using a resolver tag. In order to use validations, a resolver must be used. Resolvers are tags such as `url-param`, `query`, `body`, `form`, or `header`.

func (ErrFieldsWithoutResolver) Error

func (e ErrFieldsWithoutResolver) Error() string

type ErrInvalidBodyParser

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

ErrInvalidBodyParser indicates that a given structure has a field using a `body` loader with an invalid parser. Valid values for that tag are `json`, `xml`, `text`, `stream`, or `bytes`.

func (ErrInvalidBodyParser) Error

func (e ErrInvalidBodyParser) Error() string

type ErrInvalidFileField

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

ErrInvalidFileField indicates that a given structure has a field attempting to receive a File from the request, but has an invalid type. Raggett expects the file field be either a pointer, or a pointer slice of multipart.FileHeader or raggett.FileHeader, the latter being an alias to the former.

func (ErrInvalidFileField) Error

func (e ErrInvalidFileField) Error() string

type ErrInvalidPattern

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

ErrInvalidPattern indicates that a given structure contains a field using a `pattern` tag whose contents could not be compiled into a RegExp instance.

func (ErrInvalidPattern) Error

func (e ErrInvalidPattern) Error() string

type ErrMultipleBodyTags

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

ErrMultipleBodyTags indicates that a given structure have more than one field using a `body` tag.

func (ErrMultipleBodyTags) Error

func (e ErrMultipleBodyTags) Error() string

type ErrMultipleResolver

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

ErrMultipleResolver indicates that a given structure has a field using more than one resolver. Fields must not have more than one of the following tags: `url-param`, `query`, `body`, `form`, `header`.

func (ErrMultipleResolver) Error

func (e ErrMultipleResolver) Error() string

type Error

type Error struct {
	StackTrace    []StackFrame
	OriginalError error
}

func (Error) Error

func (e Error) Error() string

func (Error) Stack

func (e Error) Stack() string

func (Error) String

func (e Error) String() string

type ErrorHandlerFunc

type ErrorHandlerFunc func(err error, w http.ResponseWriter, r *Request)

ErrorHandlerFunc represents a function responsible for handling runtime errors. Any captured exceptions will be passed to this function. Although both http.ResponseWriter and *Request are provided, it is not guaranteed that http.ResponseWriter have not already flushed its headers. This function can be used for logging, and returning custom error messages to clients.

type FileHeader

type FileHeader multipart.FileHeader

FileHeader is a convenience type for multipart.FileHeader. When using Raggett, both types are interchangeable.

type HTMLResponder

type HTMLResponder interface {
	HTML() string
}

type JSONResponder

type JSONResponder interface {
	JSON() interface{}
}

type MediaType

type MediaType struct {
	// TypeString represents the main type of the media type. For instance, for
	// "text/plain", TypeString will contain "text".
	TypeString string

	// SubTypeString represents the main type of the media type. For instance,
	// for "text/plain", SubTypeString will contain "plain".
	SubTypeString string

	// Parameters represents the list of parameters for a parsed media type.
	// For instance, for "text/plain;foo=bar", Parameters will have as its
	// contents a map[string][]string{"foo": {"bar"}}
	Parameters map[string][]string

	// Weight indicates the weight of this particular media type. For instance,
	// for "text/plain;q=0.8", Weight will equal 0.8.
	Weight float32

	// Specificity indicates the specificity level of this MediaType. See
	// MediaTypeSpecificity for further information.
	Specificity MediaTypeSpecificity

	// IsVendor indicates whether the media type is vendored. For instance,
	// "application/vnd.raggett.example+json" is considered to be vendored.
	IsVendor bool
}

MediaType represents a media type object commonly transferred through Accept and Content-Type headers.

func MediaTypeFromString

func MediaTypeFromString(mediaType, subType string) MediaType

MediaTypeFromString takes a type and subType strings, and returns a MediaType object representing that type.

func NegotiateContentType

func NegotiateContentType(r *http.Request, offers []string) (parsed, valid bool, selected MediaType)

NegotiateContentType takes a http.Request and a list of strings containing media types in the "type/subType" format, attempts to negotiate one of the offered types with the values provided by the Client. Panics in case any content type is invalid, contains a wildcard, or extra parameters. This function converts the provided list of offers into a slice of MediaType and invokes NegotiateContentTypeWithMediaTypes.

func NegotiateContentTypeWithMediaTypes

func NegotiateContentTypeWithMediaTypes(r *http.Request, mediaOffers []MediaType) (parsed, valid bool, selected MediaType)

NegotiateContentTypeWithMediaTypes takes a http.Request and a slice of MediaType, and attempts to negotiate one of the offered types with the values provided by the Client. Panics in case the list of offers is empty. Returns whether the Accept header provided by the client could be `parsed`, whether one of the offerings matched (`valid`), and either the matched media type, or the first non-vendored media type provided through mediaOffers.

func UTF8MediaTypeFromString

func UTF8MediaTypeFromString(mediaType, subType string) MediaType

UTF8MediaTypeFromString is a utility method that invokes MediaTypeFromString passing the provided parameters, but adds an extra "charset" parameter containing the string "utf-8".

func (MediaType) String

func (mt MediaType) String() string

String returns the media type string including any provided parameters.

func (MediaType) Type

func (mt MediaType) Type() string

Type returns the media type's type string without parameters.

type MediaTypeSpecificity

type MediaTypeSpecificity int

MediaTypeSpecificity indicates the specificity level of a MediaType instance.

const (
	// MediaTypeSpecificityFullyDefined indicates the media type is fully
	// defined, containing both a type and subtype.
	MediaTypeSpecificityFullyDefined MediaTypeSpecificity = iota

	// MediaTypeSpecificityPartiallyDefined indicates the media type has a
	// wildcard value on either its Type or SubType.
	MediaTypeSpecificityPartiallyDefined

	// MediaTypeSpecificityUndefined indicates the media type contains wildcards
	// on both Type and SubType.
	MediaTypeSpecificityUndefined
)

type Mux

type Mux struct {

	// Development defines whether the application is running in a development
	// environment. When set to true, error responses generated by Raggett will
	// include extra information about the runtime in order to aid development.
	// It is recommended to set this option to false on production environments,
	// since it may expose sensitive information for third-party.
	Development bool

	// MaxMemory defines the max memory allowed to be consumed for files on
	// a per-request basis. Files greater than this value will automatically be
	// flushed to a temporary location. The default value for this parameter is
	// 32 MB.
	MaxMemory int64
	// contains filtered or unexported fields
}

func NewMux

func NewMux(logger *zap.Logger) *Mux

func (*Mux) Connect

func (mx *Mux) Connect(pattern string, handlerFn interface{})

Connect adds the route `pattern` that matches a CONNECT http method to execute the `handlerFn` function, which must simply take a Request-based struct and return an optional error.

func (*Mux) Delete

func (mx *Mux) Delete(pattern string, handlerFn interface{})

Delete adds the route `pattern` that matches a DELETE http method to execute the `handlerFn` function, which must simply take a Request-based struct and return an optional error.

func (*Mux) Get

func (mx *Mux) Get(pattern string, handlerFn interface{})

Get adds the route `pattern` that matches a GET http method to execute the `handlerFn` function, which must simply take a Request-based struct and return an optional error.

func (*Mux) HandleError

func (mx *Mux) HandleError(handlerFunc ErrorHandlerFunc)

HandleError sets the error handler for errors returned from requests or errors that occurs during the request processing. Validation errors do not call this handler, instead, use HandleValidationError. The default implementation responds using an internal handler that attempts to return an appropriate format depending on the Accept header provided by the client. When Development is set, extra information will be included in the response. Otherwise, a simpler error message will be returned.

func (*Mux) HandleValidationError

func (mx *Mux) HandleValidationError(handlerFunc ValidationErrorHandlerFunc)

HandleValidationError sets the error handler for validation errors. Validation errors are caused by requests that does not satisfy the request handler conditions (by using validation tags). The default implementation responds using an internal handler that attempts to return an appropriate format depending on the Accept header provided by the client. When Development is set, extra information will be included in the response. Otherwise, a simpler error message will be returned.

func (*Mux) Head

func (mx *Mux) Head(pattern string, handlerFn interface{})

Head adds the route `pattern` that matches a HEAD http method to execute the `handlerFn` function, which must simply take a Request-based struct and return an optional error.

func (*Mux) LogWith

func (mx *Mux) LogWith(opts ...zap.Field)

LogWith updates Raggett's logger instance to add structured context to it. Fields added here will be present in all requests, and do not affect the parent logger.

func (*Mux) MethodNotAllowed

func (mx *Mux) MethodNotAllowed(handler http.HandlerFunc)

MethodNotAllowed sets a custom http.HandlerFunc for routing paths where the method is unresolved. The default handler returns a 405 with an empty body.

func (*Mux) NotFound

func (mx *Mux) NotFound(handler http.HandlerFunc)

NotFound sets a custom http.HandlerFunc for routing paths that could not be found. The default 404 handler is `http.NotFound`.

func (*Mux) Options

func (mx *Mux) Options(pattern string, handlerFn interface{})

Options adds the route `pattern` that matches a OPTIONS http method to execute the `handlerFn` function, which must simply take a Request-based struct and return an optional error.

func (*Mux) Patch

func (mx *Mux) Patch(pattern string, handlerFn interface{})

Patch adds the route `pattern` that matches a PATCH http method to execute the `handlerFn` function, which must simply take a Request-based struct and return an optional error.

func (*Mux) Post

func (mx *Mux) Post(pattern string, handlerFn interface{})

Post adds the route `pattern` that matches a POST http method to execute the `handlerFn` function, which must simply take a Request-based struct and return an optional error.

func (*Mux) Put

func (mx *Mux) Put(pattern string, handlerFn interface{})

Put adds the route `pattern` that matches a PUT http method to execute the `handlerFn` function, which must simply take a Request-based struct and return an optional error.

func (*Mux) RequestIdentifierGenerator

func (mx *Mux) RequestIdentifierGenerator(fn RequestIdentifierGenerator)

RequestIdentifierGenerator sets a function responsible for returning a unique identifier for each incoming request. This identifier will be shown in every log entry generated by the request, and also returned through a Request-ID header on responses. The default implementation simply generates a UUID.

func (*Mux) ServeHTTP

func (mx *Mux) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP is the single method of the http.Handler interface that makes Mux interoperable with the standard library. It simply delegates the request to the internal chi.Mux instance.

func (*Mux) Trace

func (mx *Mux) Trace(pattern string, handlerFn interface{})

Trace adds the route `pattern` that matches a TRACE http method to execute the `handlerFn` function, which must simply take a Request-based struct and return an optional error.

func (*Mux) Use

func (mx *Mux) Use(middlewares ...func(http.Handler) http.Handler)

Use appends a middleware handler to the Mux middleware stack.

The middleware stack for any Mux will execute before searching for a matching route to a specific handler, which provides opportunity to respond early, change the course of the request execution, or set request-scoped values for the next http.Handler.

func (*Mux) UseLogOpts added in v0.1.5

func (mx *Mux) UseLogOpts(opts ...zap.Field) *Mux

UseLogOpts returns a Mux copy using the provided opts as the Logger options without affecting the parent Logger instance.

func (*Mux) With

func (mx *Mux) With(middlewares ...func(http.Handler) http.Handler) *Mux

With adds inline middlewares for an endpoint handler.

type PlainTextResponder

type PlainTextResponder interface {
	PlainText() string
}

type Request

type Request struct {
	// HTTPRequest represents the original http.Request received by the server
	HTTPRequest *http.Request
	// Logger represents the logger for this specific request. Logs emitted
	// through it will contain the generated unique request ID for tracing.
	Logger *zap.Logger
	// contains filtered or unexported fields
}

Request represents a Raggett request. This struct provides useful abstractions for handling requests and responses.

func NewRequest

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

NewRequest creates a new request with an empty mux. This method is intended for testing purposes.

func (*Request) Abort

func (r *Request) Abort()

Abort immediately cancels the current Request

func (*Request) AbortError

func (r *Request) AbortError(err error)

AbortError aborts the current request with a provided error.

func (*Request) AddCookie added in v0.1.9

func (r *Request) AddCookie(cookie interface{})

AddCookie adds a given cookie to the request. This method accepts either a (*)http.Cookie, or the result of invoking Cookie. Panics in case the provided value is not a http.Cookie, *http.Cookie, ChainedCookie or *ChainedCookie. Panics in case the provided object is nil.

func (*Request) AddHeader

func (r *Request) AddHeader(name, value string)

AddHeader invokes http.Header.Add for the current request's response.

func (*Request) ClientAccepts

func (r *Request) ClientAccepts() []MediaType

ClientAccepts parses the contents of the Accept header provided by the client and returns a slice of MediaType structs.

func (*Request) Context added in v0.1.9

func (r *Request) Context() context.Context

Context is a convenience method for r.HTTPRequest.Context()

func (*Request) GetCookie added in v0.1.9

func (r *Request) GetCookie(name string) (*http.Cookie, bool)

GetCookie returns a cookie with a given name, along with a boolean indicating whether the cookie is present in the request. When the returned boolean is false, the returned cookie value is nil.

func (*Request) NotFound

func (r *Request) NotFound()

NotFound aborts the current request and returns a NotFound error to the client.

func (*Request) Redirect added in v0.1.8

func (r *Request) Redirect(url string)

Redirect sets the necessary headers and status for the client to be redirected to another location. After calling this method, all headers will be flushed and no response body can be provided.

func (*Request) RequestID added in v0.1.7

func (r *Request) RequestID() string

RequestID returns the unique identifier for the current request

func (*Request) Respond

func (r *Request) Respond(value interface{})

Respond sets the response value for this Request to the provided value. Use it with structs implementing JSONResponder, XMLResponder, HTMLResponder, PlainTextResponder, BytesResponder, and/or CustomResponder. By providing a struct implementing one or more responders allows Ragget to automatically negotiate which representation will be returned to the client.

func (*Request) RespondBytes

func (r *Request) RespondBytes(buffer []byte)

RespondBytes returns a provided byte slice to the client as the response body. The contents will be sent to the client once the handler function returns.

func (*Request) RespondJSON

func (r *Request) RespondJSON(data interface{})

RespondJSON responds the provided data to the client using a JSON Content-Type. The value will be written to the client once the handler function returns. The provided value must be compatible with encoding/json marshaller.

func (*Request) RespondReader

func (r *Request) RespondReader(file io.ReadCloser)

RespondReader responds the provided io.ReadCloser to the client using an application/octet-stream Content-Type (unless SetContentType is used). Once the handler function returns, contents of the provided reader are copied to the response stream, and the reader is automatically closed.

func (*Request) RespondString

func (r *Request) RespondString(str string)

RespondString returns a provided string to the client as the response body. The contents will be sent to the client once the handler function returns.

func (*Request) RespondXML

func (r *Request) RespondXML(data interface{})

RespondXML responds the provided data to the client using an XML Content-Type. The value will be written to the client once the handler function returns. The provided value must be compatible with encoding/xml marshaller.

func (*Request) SetContentType

func (r *Request) SetContentType(contentType string)

SetContentType defines the value for the Content-Type header for this request's response. Calling this function prevents Raggett from automatically inferring the response's Content-Type.

func (*Request) SetHeader

func (r *Request) SetHeader(name, value string)

SetHeader invokes http.Header.Set for the current request's response.

func (*Request) SetStatus

func (r *Request) SetStatus(httpStatus int)

SetStatus defines which HTTP Status will be returned to the client. This method does not write headers to the client.

type RequestIdentifierGenerator

type RequestIdentifierGenerator func(*http.Request) string

RequestIdentifierGenerator represents a function that returns a unique identifier for requests handled by the Mux.

type StackFrame

type StackFrame struct {
	ProgramCounter uintptr
	Func           string
	File           string
	Line           int
}

type ValidationError

type ValidationError struct {
	StructName      string
	StructFieldName string
	FieldName       string
	FieldKind       fieldKind
	ErrorKind       ValidationErrorKind
	OriginalError   error
}

func (ValidationError) Error

func (v ValidationError) Error() string

type ValidationErrorHandlerFunc

type ValidationErrorHandlerFunc func(err ValidationError, w http.ResponseWriter, r *Request)

ValidationErrorHandlerFunc represents a function responsible for handling validation errors before a handler is invoked. This function can bbe used to provide custom error messages to clients.

type ValidationErrorKind

type ValidationErrorKind int
const (
	ValidationErrorKindBlank ValidationErrorKind = iota
	ValidationErrorKindPattern
	ValidationErrorKindRequired
	ValidationErrorKindParsing
)

func (ValidationErrorKind) Name

func (v ValidationErrorKind) Name() string

func (ValidationErrorKind) String

func (v ValidationErrorKind) String() string

type XMLResponder

type XMLResponder interface {
	XML() interface{}
}

Directories

Path Synopsis
generators

Jump to

Keyboard shortcuts

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