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 ¶
- Variables
- func AddCompressMimeType(maintype, subtypePattern string)
- type Context
- func (c *Context) AddLogField(key string, value interface{})
- func (c *Context) BasicAuth() (username, password string, ok bool)
- func (c *Context) Bind(v interface{}) error
- func (c *Context) Compressed() bool
- func (c *Context) ContentLength() int64
- func (c *Context) Cookie(name string) (*http.Cookie, error)
- func (c *Context) Data(key interface{}) interface{}
- func (c *Context) Error(code int, message string) error
- func (c *Context) Form(key string) string
- func (c *Context) FormFile(key string) (multipart.File, *multipart.FileHeader, error)
- func (c *Context) Header(key string) string
- func (c *Context) IsWrote() bool
- func (c *Context) Param(key string) string
- func (c *Context) Params() []string
- func (c *Context) Query(key string) string
- func (c *Context) RealIP() string
- func (c *Context) Redirect(code int, url string) error
- func (c *Context) ServeContent(name string, modtime time.Time, content io.ReadSeeker) error
- func (c *Context) ServeFile(name string) error
- func (c *Context) SetContentType(contentType string)
- func (c *Context) SetCookie(cookie *http.Cookie)
- func (c *Context) SetData(key, value interface{})
- func (c *Context) SetHeader(key, value string)
- func (c *Context) SetStatus(code int)
- func (c *Context) Status() int
- func (c *Context) Write(data interface{}) (err error)
- type Encoder
- type Error
- type Handler
- func Data(data interface{}, contentType string) Handler
- func ErrorHandler(err *Error) Handler
- func File(name string) Handler
- func Files(dir string) Handler
- func HTTPFiles(files http.FileSystem, index string) Handler
- func HTTPHandler(h http.Handler) Handler
- func Handlers(handlers ...Handler) Handler
- func Redirect(url string) Handler
- type JSON
- type Methods
- type Paths
- type RedirectURL
- type ServeMux
Constants ¶
This section is empty.
Variables ¶
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.
var ( ErrBadRequest = &Error{400, "bad request"} 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"} )
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.
var ( NotFound = ErrorHandler(ErrNotFound) NotImplemented = ErrorHandler(ErrNotImplemented) )
Predefined error handlers.
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 ¶
AddLogField add named filed to context log.
func (*Context) BasicAuth ¶
BasicAuth returns the username and password provided in the request's Authorization header, if the request uses HTTP Basic Authentication.
func (*Context) Bind ¶
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 ¶
Compressed returns true if response compression supported.
func (*Context) ContentLength ¶
ContentLength returns the uncompressed size of the response data.
func (*Context) Cookie ¶
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 ¶
Error replies to the request with the specified error message and HTTP code. The error message should be plain text.
func (*Context) Form ¶
Form returns the first value for the named component of the POST or PUT request body. URL query parameters are ignored.
func (*Context) IsWrote ¶
IsWrote returns true if the header has already been sent in response to the request.
func (*Context) RealIP ¶
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 ¶
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 ¶
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) SetContentType ¶
SetContentType sets response content-type header.
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. :)
type Error ¶
Error describes the status and text message to send to a HTTP request.
type Handler ¶
Handler describes an HTTP request handler.
func ErrorHandler ¶
ErrorHandler returns the handler of http requests, which always returns the specified error.
func Files ¶
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 ¶
HTTPHandler преобразует http.Handler в Handler.
func Handlers ¶
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.
type JSON ¶
type JSON = map[string]interface{}
JSON is just a quick way to describe data structures.
type Paths ¶
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 ¶
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 ¶
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 ¶
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 ¶
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.