Files
echo/context.go
T

448 lines
11 KiB
Go
Raw Normal View History

2015-03-27 14:21:30 -07:00
package echo
2015-03-01 09:45:13 -08:00
import (
"encoding/json"
2015-07-11 15:20:59 -04:00
"encoding/xml"
"io"
"mime"
"mime/multipart"
2015-03-01 09:45:13 -08:00
"net/http"
"os"
2016-03-12 05:14:15 -08:00
"path"
2015-10-16 07:51:42 -07:00
"path/filepath"
2015-12-03 17:23:53 -08:00
"time"
2015-12-21 15:20:49 -08:00
"github.com/labstack/echo/engine"
2016-03-06 09:52:32 -08:00
"github.com/labstack/gommon/log"
2015-12-04 08:13:26 -08:00
2015-07-05 11:08:17 -07:00
"net/url"
2015-10-02 11:23:52 -07:00
"bytes"
2015-10-13 07:09:53 -07:00
2015-12-21 15:20:49 -08:00
netContext "golang.org/x/net/context"
2015-03-01 09:45:13 -08:00
)
type (
2016-03-19 15:47:20 -07:00
// Context represents the context of the current HTTP request. It holds request and
// response objects, path, path parameters, data and registered handler.
2015-12-03 17:23:53 -08:00
Context interface {
2015-12-21 15:20:49 -08:00
netContext.Context
2016-03-19 15:47:20 -07:00
// NetContext returns `http://blog.golang.org/context.Context` interface.
2016-03-14 12:21:47 -07:00
NetContext() netContext.Context
2016-03-19 15:47:20 -07:00
// SetNetContext sets `http://blog.golang.org/context.Context` interface.
2016-03-14 19:58:46 -07:00
SetNetContext(netContext.Context)
2016-03-19 15:47:20 -07:00
// Request returns `engine.Request` interface.
2015-12-21 15:20:49 -08:00
Request() engine.Request
2016-03-19 15:47:20 -07:00
// Request returns `engine.Response` interface.
2015-12-21 15:20:49 -08:00
Response() engine.Response
2016-03-19 15:47:20 -07:00
// Path returns the registered path for the handler.
2015-12-03 17:23:53 -08:00
Path() string
2016-03-19 15:47:20 -07:00
// P returns path parameter by index.
2015-12-03 17:23:53 -08:00
P(int) string
2016-03-19 15:47:20 -07:00
// Param returns path parameter by name.
2015-12-03 17:23:53 -08:00
Param(string) string
2016-03-19 15:47:20 -07:00
// ParamNames returns path parameter names.
2016-03-05 20:03:11 -08:00
ParamNames() []string
2016-03-19 15:47:20 -07:00
// QueryParam returns the query param for the provided name. It is an alias
// for `engine.URL#QueryParam()`.
QueryParam(string) string
2016-03-19 15:47:20 -07:00
2016-03-23 11:10:22 -05:00
// QueryParam returns the query parameters as map. It is an alias for `engine.URL#QueryParams()`.
QueryParams() map[string][]string
// FormValue returns the form field value for the provided name. It is an
// alias for `engine.Request#FormValue()`.
FormValue(string) string
2016-03-23 11:10:22 -05:00
// FormParams returns the form parameters as map. It is an alias for `engine.Request#FormParams()`.
FormParams() map[string][]string
// FormFile returns the multipart form file for the provided name. It is an
// alias for `engine.Request#FormFile()`.
FormFile(string) (*multipart.FileHeader, error)
// MultipartForm returns the multipart form. It is an alias for `engine.Request#MultipartForm()`.
MultipartForm() (*multipart.Form, error)
2016-03-19 15:47:20 -07:00
// Get retrieves data from the context.
2015-12-03 17:23:53 -08:00
Get(string) interface{}
2016-03-19 15:47:20 -07:00
// Set saves data in the context.
2016-03-14 19:58:46 -07:00
Set(string, interface{})
2016-03-19 15:47:20 -07:00
// Bind binds the request body into provided type `i`. The default binder does
// it based on Content-Type header.
2015-12-03 17:23:53 -08:00
Bind(interface{}) error
2016-03-19 15:47:20 -07:00
// Render renders a template with data and sends a text/html response with status
// code. Templates can be registered using `Echo.SetRenderer()`.
2015-12-03 17:23:53 -08:00
Render(int, string, interface{}) error
2016-03-19 15:47:20 -07:00
// HTML sends an HTTP response with status code.
2015-12-03 17:23:53 -08:00
HTML(int, string) error
2016-03-19 15:47:20 -07:00
// String sends a string response with status code.
2015-12-03 17:23:53 -08:00
String(int, string) error
2016-03-19 15:47:20 -07:00
// JSON sends a JSON response with status code.
2015-12-03 17:23:53 -08:00
JSON(int, interface{}) error
2016-03-19 15:47:20 -07:00
// JSONBlob sends a JSON blob response with status code.
JSONBlob(int, []byte) error
2016-03-19 15:47:20 -07:00
// JSONP sends a JSONP response with status code. It uses `callback` to construct
// the JSONP payload.
2015-12-03 17:23:53 -08:00
JSONP(int, string, interface{}) error
2016-03-19 15:47:20 -07:00
// XML sends an XML response with status code.
2015-12-03 17:23:53 -08:00
XML(int, interface{}) error
2016-03-19 15:47:20 -07:00
// XMLBlob sends a XML blob response with status code.
XMLBlob(int, []byte) error
2016-03-19 15:47:20 -07:00
// File sends a response with the content of the file.
2016-03-12 05:14:15 -08:00
File(string) error
2016-03-19 15:47:20 -07:00
// Attachment sends a response from `io.Reader` as attachment, prompting client
// to save the file.
2016-03-12 11:49:45 -08:00
Attachment(io.Reader, string) error
2016-03-19 15:47:20 -07:00
// NoContent sends a response with no body and a status code.
2015-12-03 17:23:53 -08:00
NoContent(int) error
2016-03-19 15:47:20 -07:00
// Redirect redirects the request with status code.
2015-12-03 17:23:53 -08:00
Redirect(int, string) error
2016-03-19 15:47:20 -07:00
// Error invokes the registered HTTP error handler. Generally used by middleware.
2015-12-03 17:23:53 -08:00
Error(err error)
2016-03-19 15:47:20 -07:00
// Handler implements `Handler` interface.
Handle(Context) error
2016-03-19 15:47:20 -07:00
// Logger returns the `Logger` instance.
2016-03-06 09:52:32 -08:00
Logger() *log.Logger
2016-03-19 15:47:20 -07:00
// Echo returns the `Echo` instance.
2016-02-18 14:04:28 -08:00
Echo() *Echo
2016-03-19 15:47:20 -07:00
// Object returns the `context` instance.
2016-02-08 16:48:03 -08:00
Object() *context
2016-03-19 15:47:20 -07:00
// Reset resets the context after request completes. It must be called along
// with `Echo#GetContext()` and `Echo#PutContext()`. See `Echo#ServeHTTP()`
Reset(engine.Request, engine.Response)
2015-12-03 17:23:53 -08:00
}
context struct {
2016-03-14 08:09:48 -07:00
netContext netContext.Context
request engine.Request
response engine.Response
path string
pnames []string
pvalues []string
query url.Values
store store
handler Handler
echo *Echo
2015-03-01 09:45:13 -08:00
}
2015-12-03 17:23:53 -08:00
2015-03-01 09:45:13 -08:00
store map[string]interface{}
)
const (
indexPage = "index.html"
)
2015-05-28 16:50:49 -07:00
// NewContext creates a Context object.
2016-03-21 17:27:14 -07:00
func NewContext(rq engine.Request, rs engine.Response, e *Echo) Context {
2015-12-03 17:23:53 -08:00
return &context{
2016-03-21 17:27:14 -07:00
request: rq,
response: rs,
echo: e,
2015-06-03 15:18:27 -07:00
pvalues: make([]string, *e.maxParam),
store: make(store),
handler: notFoundHandler,
}
}
2016-03-14 12:21:47 -07:00
func (c *context) NetContext() netContext.Context {
return c.netContext
}
2016-03-14 19:58:46 -07:00
func (c *context) SetNetContext(ctx netContext.Context) {
c.netContext = ctx
}
2015-12-03 17:23:53 -08:00
func (c *context) Deadline() (deadline time.Time, ok bool) {
2016-03-14 08:09:48 -07:00
return c.netContext.Deadline()
2015-12-03 17:23:53 -08:00
}
func (c *context) Done() <-chan struct{} {
2016-03-14 08:09:48 -07:00
return c.netContext.Done()
2015-12-03 17:23:53 -08:00
}
func (c *context) Err() error {
2016-03-14 08:09:48 -07:00
return c.netContext.Err()
2015-12-03 17:23:53 -08:00
}
func (c *context) Value(key interface{}) interface{} {
2016-03-14 08:09:48 -07:00
return c.netContext.Value(key)
}
func (c *context) Handle(ctx Context) error {
return c.handler.Handle(ctx)
2015-12-03 17:23:53 -08:00
}
2015-12-21 15:20:49 -08:00
func (c *context) Request() engine.Request {
return c.request
}
2015-12-21 15:20:49 -08:00
func (c *context) Response() engine.Response {
return c.response
}
2015-12-03 17:23:53 -08:00
func (c *context) Path() string {
2015-11-12 20:23:14 -08:00
return c.path
}
2015-12-03 17:23:53 -08:00
func (c *context) P(i int) (value string) {
2015-06-05 15:08:32 -07:00
l := len(c.pnames)
2015-06-20 18:56:51 -07:00
if i < l {
2015-04-25 22:32:20 -07:00
value = c.pvalues[i]
}
return
2015-03-01 09:45:13 -08:00
}
2015-12-03 17:23:53 -08:00
func (c *context) Param(name string) (value string) {
2015-04-26 09:48:49 -07:00
l := len(c.pnames)
2015-04-25 22:32:20 -07:00
for i, n := range c.pnames {
2015-06-20 18:56:51 -07:00
if n == name && i < l {
2015-04-25 22:32:20 -07:00
value = c.pvalues[i]
break
2015-04-05 20:08:52 -07:00
}
}
return
2015-03-01 09:45:13 -08:00
}
2016-03-05 20:03:11 -08:00
func (c *context) ParamNames() []string {
return c.pnames
}
func (c *context) QueryParam(name string) string {
return c.request.URL().QueryParam(name)
2015-07-05 11:08:17 -07:00
}
2016-03-23 11:10:22 -05:00
func (c *context) QueryParams() map[string][]string {
return c.request.URL().QueryParams()
}
func (c *context) FormValue(name string) string {
2016-01-28 23:46:11 -08:00
return c.request.FormValue(name)
2015-07-05 11:08:17 -07:00
}
2016-03-23 11:10:22 -05:00
func (c *context) FormParams() map[string][]string {
return c.request.FormParams()
}
func (c *context) FormFile(name string) (*multipart.FileHeader, error) {
return c.request.FormFile(name)
}
func (c *context) MultipartForm() (*multipart.Form, error) {
return c.request.MultipartForm()
}
2015-12-03 17:23:53 -08:00
func (c *context) Set(key string, val interface{}) {
2015-07-14 10:56:23 -07:00
if c.store == nil {
c.store = make(store)
}
2015-05-30 10:54:55 -07:00
c.store[key] = val
}
2016-03-14 19:58:46 -07:00
func (c *context) Get(key string) interface{} {
return c.store[key]
}
2015-12-03 17:23:53 -08:00
func (c *context) Bind(i interface{}) error {
2016-03-05 20:03:11 -08:00
return c.echo.binder.Bind(i, c)
2015-03-01 09:45:13 -08:00
}
2015-12-03 17:23:53 -08:00
func (c *context) Render(code int, name string, data interface{}) (err error) {
2015-04-10 21:48:26 -07:00
if c.echo.renderer == nil {
return ErrRendererNotRegistered
2015-04-10 21:48:26 -07:00
}
2015-10-06 06:48:33 -07:00
buf := new(bytes.Buffer)
2016-03-05 20:03:11 -08:00
if err = c.echo.renderer.Render(buf, name, data, c); err != nil {
2015-10-02 11:23:52 -07:00
return
}
2015-07-22 04:44:29 -07:00
c.response.Header().Set(ContentType, TextHTMLCharsetUTF8)
c.response.WriteHeader(code)
2016-03-12 15:06:52 -08:00
_, err = c.response.Write(buf.Bytes())
2015-10-02 11:23:52 -07:00
return
2015-03-29 23:35:08 -07:00
}
2015-12-03 17:23:53 -08:00
func (c *context) HTML(code int, html string) (err error) {
2015-07-22 04:44:29 -07:00
c.response.Header().Set(ContentType, TextHTMLCharsetUTF8)
2015-07-08 13:51:08 -07:00
c.response.WriteHeader(code)
2016-03-12 15:06:52 -08:00
_, err = c.response.Write([]byte(html))
2015-07-08 13:51:08 -07:00
return
}
2015-12-03 17:23:53 -08:00
func (c *context) String(code int, s string) (err error) {
2015-12-01 11:22:45 -08:00
c.response.Header().Set(ContentType, TextPlainCharsetUTF8)
2015-07-11 15:20:59 -04:00
c.response.WriteHeader(code)
2016-03-12 15:06:52 -08:00
_, err = c.response.Write([]byte(s))
2015-07-11 15:20:59 -04:00
return
}
2015-12-03 17:23:53 -08:00
func (c *context) JSON(code int, i interface{}) (err error) {
2015-11-08 00:39:09 +01:00
b, err := json.Marshal(i)
if c.echo.Debug() {
b, err = json.MarshalIndent(i, "", " ")
}
2015-11-08 00:39:09 +01:00
if err != nil {
return err
}
return c.JSONBlob(code, b)
}
func (c *context) JSONBlob(code int, b []byte) (err error) {
2015-11-08 00:39:09 +01:00
c.response.Header().Set(ContentType, ApplicationJSONCharsetUTF8)
c.response.WriteHeader(code)
2016-03-12 15:06:52 -08:00
_, err = c.response.Write(b)
2015-11-08 00:39:09 +01:00
return
2015-11-01 19:48:55 +01:00
}
2015-12-03 17:23:53 -08:00
func (c *context) JSONP(code int, callback string, i interface{}) (err error) {
2015-10-02 11:23:52 -07:00
b, err := json.Marshal(i)
if err != nil {
return err
}
2015-07-24 15:28:35 -04:00
c.response.Header().Set(ContentType, ApplicationJavaScriptCharsetUTF8)
c.response.WriteHeader(code)
2016-03-12 15:06:52 -08:00
if _, err = c.response.Write([]byte(callback + "(")); err != nil {
return
}
if _, err = c.response.Write(b); err != nil {
return
}
_, err = c.response.Write([]byte(");"))
2015-07-24 15:28:35 -04:00
return
}
2015-12-03 17:23:53 -08:00
func (c *context) XML(code int, i interface{}) (err error) {
2015-10-02 11:23:52 -07:00
b, err := xml.Marshal(i)
if c.echo.Debug() {
b, err = xml.MarshalIndent(i, "", " ")
}
2015-10-02 11:23:52 -07:00
if err != nil {
return err
}
return c.XMLBlob(code, b)
}
func (c *context) XMLBlob(code int, b []byte) (err error) {
2015-07-22 04:44:29 -07:00
c.response.Header().Set(ContentType, ApplicationXMLCharsetUTF8)
c.response.WriteHeader(code)
2016-03-12 15:06:52 -08:00
if _, err = c.response.Write([]byte(xml.Header)); err != nil {
return
}
_, err = c.response.Write(b)
2015-10-02 11:23:52 -07:00
return
2015-03-01 09:45:13 -08:00
}
2016-03-12 05:14:15 -08:00
func (c *context) File(file string) error {
root, file := filepath.Split(file)
fs := http.Dir(root)
f, err := fs.Open(file)
if err != nil {
return ErrNotFound
}
defer f.Close()
fi, _ := f.Stat()
if fi.IsDir() {
file = path.Join(file, "index.html")
f, err = fs.Open(file)
if err != nil {
return ErrNotFound
}
fi, _ = f.Stat()
}
return ServeContent(c.Request(), c.Response(), f, fi)
}
2016-03-12 11:49:45 -08:00
func (c *context) Attachment(r io.Reader, name string) (err error) {
c.response.Header().Set(ContentType, detectContentType(name))
2016-03-12 10:18:40 -08:00
c.response.Header().Set(ContentDisposition, "attachment; filename="+name)
c.response.WriteHeader(http.StatusOK)
2016-03-12 11:49:45 -08:00
_, err = io.Copy(c.response, r)
2015-10-02 11:23:52 -07:00
return
2015-07-31 19:25:03 -07:00
}
2015-12-03 17:23:53 -08:00
func (c *context) NoContent(code int) error {
c.response.WriteHeader(code)
2015-04-18 16:47:48 -07:00
return nil
}
2015-12-03 17:23:53 -08:00
func (c *context) Redirect(code int, url string) error {
if code < http.StatusMultipleChoices || code > http.StatusTemporaryRedirect {
return ErrInvalidRedirectCode
}
2016-02-20 12:54:43 -08:00
c.response.Header().Set(Location, url)
c.response.WriteHeader(code)
2015-07-20 19:24:33 -07:00
return nil
2015-05-29 17:20:13 -07:00
}
2015-12-03 17:23:53 -08:00
func (c *context) Error(err error) {
c.echo.httpErrorHandler(err, c)
}
2015-03-08 23:58:10 -07:00
2016-02-18 14:04:28 -08:00
func (c *context) Echo() *Echo {
return c.echo
}
2016-03-06 09:52:32 -08:00
func (c *context) Logger() *log.Logger {
2015-12-04 08:13:26 -08:00
return c.echo.logger
}
2016-02-08 16:48:03 -08:00
func (c *context) Object() *context {
2015-12-04 08:13:26 -08:00
return c
2015-12-01 11:22:45 -08:00
}
2016-03-19 15:47:20 -07:00
// ServeContent sends a response from `io.Reader`. It automatically sets the `Content-Type`
// and `Last-Modified` headers.
2016-03-21 17:27:14 -07:00
func ServeContent(rq engine.Request, rs engine.Response, f http.File, fi os.FileInfo) error {
rs.Header().Set(ContentType, detectContentType(fi.Name()))
rs.Header().Set(LastModified, fi.ModTime().UTC().Format(http.TimeFormat))
rs.WriteHeader(http.StatusOK)
_, err := io.Copy(rs, f)
2016-03-12 05:14:15 -08:00
return err
}
func detectContentType(name string) (t string) {
if t = mime.TypeByExtension(filepath.Ext(name)); t == "" {
t = OctetStream
}
return
}
2016-03-21 17:27:14 -07:00
func (c *context) Reset(rq engine.Request, rs engine.Response) {
2016-03-16 08:24:25 -07:00
c.netContext = nil
2016-03-21 17:27:14 -07:00
c.request = rq
c.response = rs
2015-07-13 23:36:56 -07:00
c.query = nil
2015-07-14 10:56:23 -07:00
c.store = nil
2016-03-08 19:31:11 -08:00
c.handler = notFoundHandler
2015-03-06 11:12:33 -08:00
}