rest

package module
v0.0.0-...-f403ce8 Latest Latest
Warning

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

Go to latest
Published: Aug 4, 2018 License: MIT Imports: 23 Imported by: 2

README

REST API

GoDoc Build Status Coverage Status

Package rest is designed for creating RESTful APIs.

  • makes it easy to give any objects that support serialization to JSON
  • supports the restriction of only one response to the request
  • have the ability to override the data format before output
  • it is possible to set your headers to output
  • separate support for handling redirects
  • ready for logging responses
  • support for named parameters in the path

Documentation

Overview

Package rest is designed for creating RESTful APIs.

  • makes it easy to give any objects that support serialization to JSON
  • supports the restriction of only one response to the request
  • have the ability to override the data format before output
  • it is possible to set your headers to output
  • separate support for handling redirects
  • ready for logging responses
  • support for named parameters in the path

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrUnsupportedCharset     = &Error{400, "unsupported charset"}
	ErrEmptyContentType       = &Error{400, "empty content type"}
	ErrUnsupportedContentType = &Error{400, "unsupported content type"}
	ErrUnsupportedHTTPMethod  = &Error{400, "unsupported http method"}
)

Error returned by the Bind function.

View Source
var (
	ErrBadRequest            = &Error{400, "bad request"}
	ErrUnauthorized          = &Error{401, "unauthorized"}
	ErrForbidden             = &Error{403, "forbidden"}
	ErrNotFound              = &Error{404, "not found"}
	ErrMethodNotAllowed      = &Error{405, "method not allowed"}
	ErrLengthRequired        = &Error{411, "length required"}
	ErrRequestEntityTooLarge = &Error{413, "request entity too large"}
	ErrUnsupportedMediaType  = &Error{415, "unsupported media type"}
	ErrInternalServerError   = &Error{500, "internal server error"}
	ErrMultipleResponse      = &Error{500, "multiple server response"}
	ErrNotImplemented        = &Error{501, "not implemented"}
	ErrServiceUnavailable    = &Error{503, "service unavailable"}
)

These errors are handled when passing them into a method Context.Write and set the appropriate status response.

Except this error, just checked that the error is responsible for os.IsNotExist (in this case, the status will be 404), or os.IsPermission (status 403). All other errors set the status to 500.

View Source
var (
	NotFound       = ErrorHandler(ErrNotFound)
	NotImplemented = ErrorHandler(ErrNotImplemented)
)

Predefined error handlers.

View Source
var CompressMimeTypes = map[string][]string{
	"text":        {"*"},
	"application": {"json", "*+json", "xml", "*+xml", "javascript", "x-javascript", "x-font-ttf"},
	"image":       {"*+xml", "bmp", "vnd.microsoft.icon", "x-icon"},
	"audio":       {"wave", "aiff", "basic", "x-wav"},
	"font":        {"eot", "opentype"},
}

CompressMimeTypes contains Media-Type patterns that can be compressed.

Functions

func AddCompressMimeType

func AddCompressMimeType(maintype, subtypePattern string)

AddCompressMimeType registers a new type for compression.

Types

type Context

type Context struct {
	Response      http.ResponseWriter // original http.Response
	Request       *http.Request       // original http.Request
	Encoder       Encoder             // data encoder
	AllowMultiple bool                // allow multiple response
	// contains filtered or unexported fields
}

Context describes the context of processing an http request.

func (*Context) AddLogField

func (c *Context) AddLogField(key string, value interface{})

AddLogField add named filed to context log.

func (*Context) BasicAuth

func (c *Context) BasicAuth() (username, password string, ok bool)

BasicAuth returns the username and password provided in the request's Authorization header, if the request uses HTTP Basic Authentication.

func (*Context) Bind

func (c *Context) Bind(v interface{}) error

Bind parses the request and populates the received data specified structure. Supported parsing of JSON, XML and HTTP form. For HTTP form in the structure, you can use the tag `form:` to specify the name.

func (*Context) Compressed

func (c *Context) Compressed() bool

Compressed returns true if response compression supported.

func (*Context) ContentLength

func (c *Context) ContentLength() int64

ContentLength returns the uncompressed size of the response data.

func (*Context) Cookie

func (c *Context) Cookie(name string) (*http.Cookie, error)

Cookie returns the named cookie provided in the request or http.ErrNoCookie if not found.

func (*Context) Data

func (c *Context) Data(key interface{}) interface{}

Data returns the user data stored in the request context with specified key. Usually this information is used when you want to pass them between multiple processors.

func (*Context) Error

func (c *Context) Error(code int, message string) error

Error replies to the request with the specified error message and HTTP code. The error message should be plain text.

func (*Context) Form

func (c *Context) Form(key string) string

Form returns the first value for the named component of the POST or PUT request body. URL query parameters are ignored.

func (*Context) FormFile

func (c *Context) FormFile(key string) (multipart.File, *multipart.FileHeader, error)

FormFile returns the first file for the provided form key.

func (*Context) Header

func (c *Context) Header(key string) string

Header return request header value.

func (*Context) IsWrote

func (c *Context) IsWrote() bool

IsWrote returns true if the header has already been sent in response to the request.

func (*Context) Param

func (c *Context) Param(key string) string

Param returns the value of the named parameter.

func (*Context) Params

func (c *Context) Params() []string

Params return all param names

func (*Context) Query

func (c *Context) Query(key string) string

Query returns the first value for the named component of the URL query.

func (*Context) RealIP

func (c *Context) RealIP() string

RealIP returns a real IP address from headers. To this end, we use the headers of the http request "X-Forwarded-For" and "X-Real-IP" or a real address from the connection.

func (*Context) Redirect

func (c *Context) Redirect(code int, url string) error

Redirect replies to the request with a redirect to url, which may be a path relative to the request path.

The provided code should be in the 3xx range and is usually http.StatusMovedPermanently, http.StatusFound or http.StatusSeeOther.

func (*Context) ServeContent

func (c *Context) ServeContent(name string, modtime time.Time, content io.ReadSeeker) error

ServeContent replies to the request using the content in the provided ReadSeeker. The main benefit of ServeContent over io.Copy is that it handles Range requests properly, sets the MIME type, and handles If-Modified-Since requests.

func (*Context) ServeFile

func (c *Context) ServeFile(name string) error

ServeFile replies to the request with the contents of the named file.

func (*Context) SetContentType

func (c *Context) SetContentType(contentType string)

SetContentType sets response content-type header.

func (*Context) SetCookie

func (c *Context) SetCookie(cookie *http.Cookie)

SetCookie adds the Cookie in the response.

func (*Context) SetData

func (c *Context) SetData(key, value interface{})

SetData saves the user data in the request context with the specified key.

Recommended as a key to use a private type and its the value to avoid accidental overwrites of the data to other processors: this will certainly protect against casual access to them. But strings too supported. :)

func (*Context) SetHeader

func (c *Context) SetHeader(key, value string)

SetHeader sets a response header with a given value.

func (*Context) SetStatus

func (c *Context) SetStatus(code int)

SetStatus sets response status code.

func (*Context) Status

func (c *Context) Status() int

Status returns response status code.

func (*Context) Write

func (c *Context) Write(data interface{}) (err error)

Write replies to the request with the specified using Encoder.

type Encoder

type Encoder func(*Context, interface{}) error

Encoder describes an function capable of encoding a response.

type Error

type Error struct {
	Code    int    `json:"code"`
	Message string `json:"error"`
}

Error describes the status and text message to send to a HTTP request.

func NewError

func NewError(code int, msg string) *Error

NewError returns a new error with the specified code and message.

func (*Error) Error

func (e *Error) Error() string

Error returns a textual description of the error.

type Handler

type Handler func(*Context) error

Handler describes an HTTP request handler.

func Data

func Data(data interface{}, contentType string) Handler

Data constantly gives specified in the settings data in response to the request.

func ErrorHandler

func ErrorHandler(err *Error) Handler

ErrorHandler returns the handler of http requests, which always returns the specified error.

func File

func File(name string) Handler

File returns the file content.

func Files

func Files(dir string) Handler

Files gives the files from the specified directory. The file name is set in the way as the last named parameter. Does not display the list of files if the request is for a file directory in contrast to standard functions http.FileServer.

func HTTPFiles

func HTTPFiles(files http.FileSystem, index string) Handler

HTTPFiles обеспечивает отдачу файлов с помощью http.Dir и аналогичных вещей, которые поддерживают интерфейс http.FileSystem.

func HTTPHandler

func HTTPHandler(h http.Handler) Handler

HTTPHandler преобразует http.Handler в Handler.

func Handlers

func Handlers(handlers ...Handler) Handler

Handlers combines multiple query processors in the queue. They will be executed in the order in which were added one after another until they are all done or until you return the first error, that interrupts the process further processing. As well further processing is interrupted if the handler gave the response to the client. Using this feature allows you to combine multiple processors into one.

func Redirect

func Redirect(url string) Handler

Redirect returns a Handler which performs a permanent redirect specified in the URL parameters.

func (Handler) ServeHTTP

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

ServeHTTP implements http.Handler interface.

type JSON

type JSON = map[string]interface{}

JSON is just a quick way to describe data structures.

type Methods

type Methods map[string]Handler

Methods allows one to describe handlers for methods.

type Paths

type Paths map[string]Methods

Paths allows to describe multiple handlers for different ways and methods: the key for this dictionary are path queries. Used as argument when calling the method ServeMux.Handles.

type RedirectURL

type RedirectURL struct {
	Code int    `json:"code"`
	URL  string `json:"location"`
}

RedirectURL is used for output redirect.

type ServeMux

type ServeMux struct {
	Headers map[string]string // additional http.Headers
	Encoder Encoder           // data Encoder (used default if nil)
	Logger  *log.Logger       // access logger (if not nil)
	// contains filtered or unexported fields
}

ServeMux is an HTTP request multiplexer. It matches the URL of each incoming request against a list of registered patterns and calls the handler for the pattern that most closely matches the URL.

You can use the named path elements:

/user/:name
/user/:name/files
/user/:name/files/*filename

func (*ServeMux) Handle

func (mux *ServeMux) Handle(method, pattern string, handlers ...Handler)

Handle registers the handler for the given method and pattern. If you specify multiple handlers, they will be run sequentially until one of them does not return a non-zero response status code or error. When you specify the path pattern, you can use named parameters.

func (*ServeMux) Handler

func (mux *ServeMux) Handler(c *Context) (err error)

Handler is responsible for the selection of the handler and its implementation.

If the handler for the given path and method was not found, but there are handlers for other methods, it returns the ErrMethodNotAllowed and the header is passed the list of methods that can be applied to the given path. Otherwise, returns the ErrNotFound.

func (*ServeMux) Handles

func (mux *ServeMux) Handles(paths Paths, middleware ...Handler)

Handles adds from the list of handlers for multiple ways and methods. It is, in fact, just a convenient way to immediately identify a large number of handlers, without causing every time ServeMux.Handle.

Optionally, you can specify the list of handlers to be executed before performance of the specified.

func (*ServeMux) ServeHTTP

func (mux *ServeMux) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP implements http.Handler interface.

Jump to

Keyboard shortcuts

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