1
0
mirror of https://github.com/labstack/echo.git synced 2025-07-17 01:43:02 +02:00

removed embedded context and exposed SetRequest in context

Signed-off-by: Vishal Rana <vr@labstack.com>
This commit is contained in:
Vishal Rana
2016-10-10 17:31:26 -07:00
parent 727b96f46f
commit 15eb5b0aad
8 changed files with 103 additions and 262 deletions

View File

@ -18,25 +18,18 @@ import (
"golang.org/x/net/websocket" "golang.org/x/net/websocket"
"bytes" "bytes"
"github.com/labstack/echo/context"
) )
type ( type (
// Context represents the context of the current HTTP request. It holds request and // Context represents the context of the current HTTP request. It holds request and
// response objects, path, path parameters, data and registered handler. // response objects, path, path parameters, data and registered handler.
Context interface { Context interface {
context.Context
// StdContext returns `context.Context`.
StdContext() context.Context
// SetStdContext sets `context.Context`.
SetStdContext(context.Context)
// Request returns `*http.Request`. // Request returns `*http.Request`.
Request() *http.Request Request() *http.Request
// SetWebSocket sets `*http.Request`.
SetRequest(*http.Request)
// Request returns `*Response`. // Request returns `*Response`.
Response() *Response Response() *Response
@ -199,8 +192,7 @@ type (
Reset(*http.Request, http.ResponseWriter) Reset(*http.Request, http.ResponseWriter)
} }
echoContext struct { context struct {
context context.Context
request *http.Request request *http.Request
response *Response response *Response
webSocket *websocket.Conn webSocket *websocket.Conn
@ -209,8 +201,11 @@ type (
pvalues []string pvalues []string
query url.Values query url.Values
handler HandlerFunc handler HandlerFunc
store store
echo *Echo echo *Echo
} }
store map[string]interface{}
) )
const ( const (
@ -218,51 +213,31 @@ const (
indexPage = "index.html" indexPage = "index.html"
) )
func (c *echoContext) StdContext() context.Context { func (c *context) Request() *http.Request {
return c.context
}
func (c *echoContext) SetStdContext(ctx context.Context) {
c.context = ctx
}
func (c *echoContext) Deadline() (deadline time.Time, ok bool) {
return c.context.Deadline()
}
func (c *echoContext) Done() <-chan struct{} {
return c.context.Done()
}
func (c *echoContext) Err() error {
return c.context.Err()
}
func (c *echoContext) Value(key interface{}) interface{} {
return c.context.Value(key)
}
func (c *echoContext) Request() *http.Request {
return c.request return c.request
} }
func (c *echoContext) Response() *Response { func (c *context) SetRequest(r *http.Request) {
c.request = r
}
func (c *context) Response() *Response {
return c.response return c.response
} }
func (c *echoContext) WebSocket() *websocket.Conn { func (c *context) WebSocket() *websocket.Conn {
return c.webSocket return c.webSocket
} }
func (c *echoContext) SetWebSocket(ws *websocket.Conn) { func (c *context) SetWebSocket(ws *websocket.Conn) {
c.webSocket = ws c.webSocket = ws
} }
func (c *echoContext) IsTLS() bool { func (c *context) IsTLS() bool {
return c.request.TLS != nil return c.request.TLS != nil
} }
func (c *echoContext) Scheme() string { func (c *context) Scheme() string {
// Can't use `r.Request.URL.Scheme` // Can't use `r.Request.URL.Scheme`
// See: https://groups.google.com/forum/#!topic/golang-nuts/pMUkBlQBDF0 // See: https://groups.google.com/forum/#!topic/golang-nuts/pMUkBlQBDF0
if c.IsTLS() { if c.IsTLS() {
@ -271,7 +246,7 @@ func (c *echoContext) Scheme() string {
return "http" return "http"
} }
func (c *echoContext) RealIP() string { func (c *context) RealIP() string {
ra := c.request.RemoteAddr ra := c.request.RemoteAddr
if ip := c.request.Header.Get(HeaderXForwardedFor); ip != "" { if ip := c.request.Header.Get(HeaderXForwardedFor); ip != "" {
ra = ip ra = ip
@ -283,15 +258,15 @@ func (c *echoContext) RealIP() string {
return ra return ra
} }
func (c *echoContext) Path() string { func (c *context) Path() string {
return c.path return c.path
} }
func (c *echoContext) SetPath(p string) { func (c *context) SetPath(p string) {
c.path = p c.path = p
} }
func (c *echoContext) P(i int) (value string) { func (c *context) P(i int) (value string) {
l := len(c.pnames) l := len(c.pnames)
if i < l { if i < l {
value = c.pvalues[i] value = c.pvalues[i]
@ -299,7 +274,7 @@ func (c *echoContext) P(i int) (value string) {
return return
} }
func (c *echoContext) Param(name string) (value string) { func (c *context) Param(name string) (value string) {
l := len(c.pnames) l := len(c.pnames)
for i, n := range c.pnames { for i, n := range c.pnames {
if n == name && i < l { if n == name && i < l {
@ -310,45 +285,45 @@ func (c *echoContext) Param(name string) (value string) {
return return
} }
func (c *echoContext) ParamNames() []string { func (c *context) ParamNames() []string {
return c.pnames return c.pnames
} }
func (c *echoContext) SetParamNames(names ...string) { func (c *context) SetParamNames(names ...string) {
c.pnames = names c.pnames = names
} }
func (c *echoContext) ParamValues() []string { func (c *context) ParamValues() []string {
return c.pvalues return c.pvalues
} }
func (c *echoContext) SetParamValues(values ...string) { func (c *context) SetParamValues(values ...string) {
c.pvalues = values c.pvalues = values
} }
func (c *echoContext) QueryParam(name string) string { func (c *context) QueryParam(name string) string {
if c.query == nil { if c.query == nil {
c.query = c.request.URL.Query() c.query = c.request.URL.Query()
} }
return c.query.Get(name) return c.query.Get(name)
} }
func (c *echoContext) QueryParams() url.Values { func (c *context) QueryParams() url.Values {
if c.query == nil { if c.query == nil {
c.query = c.request.URL.Query() c.query = c.request.URL.Query()
} }
return c.query return c.query
} }
func (c *echoContext) QueryString() string { func (c *context) QueryString() string {
return c.request.URL.RawQuery return c.request.URL.RawQuery
} }
func (c *echoContext) FormValue(name string) string { func (c *context) FormValue(name string) string {
return c.request.FormValue(name) return c.request.FormValue(name)
} }
func (c *echoContext) FormParams() (url.Values, error) { func (c *context) FormParams() (url.Values, error) {
if strings.HasPrefix(c.request.Header.Get(HeaderContentType), MIMEMultipartForm) { if strings.HasPrefix(c.request.Header.Get(HeaderContentType), MIMEMultipartForm) {
if err := c.request.ParseMultipartForm(defaultMemory); err != nil { if err := c.request.ParseMultipartForm(defaultMemory); err != nil {
return nil, err return nil, err
@ -361,41 +336,44 @@ func (c *echoContext) FormParams() (url.Values, error) {
return c.request.Form, nil return c.request.Form, nil
} }
func (c *echoContext) FormFile(name string) (*multipart.FileHeader, error) { func (c *context) FormFile(name string) (*multipart.FileHeader, error) {
_, fh, err := c.request.FormFile(name) _, fh, err := c.request.FormFile(name)
return fh, err return fh, err
} }
func (c *echoContext) MultipartForm() (*multipart.Form, error) { func (c *context) MultipartForm() (*multipart.Form, error) {
err := c.request.ParseMultipartForm(defaultMemory) err := c.request.ParseMultipartForm(defaultMemory)
return c.request.MultipartForm, err return c.request.MultipartForm, err
} }
func (c *echoContext) Cookie(name string) (*http.Cookie, error) { func (c *context) Cookie(name string) (*http.Cookie, error) {
return c.request.Cookie(name) return c.request.Cookie(name)
} }
func (c *echoContext) SetCookie(cookie *http.Cookie) { func (c *context) SetCookie(cookie *http.Cookie) {
http.SetCookie(c.Response(), cookie) http.SetCookie(c.Response(), cookie)
} }
func (c *echoContext) Cookies() []*http.Cookie { func (c *context) Cookies() []*http.Cookie {
return c.request.Cookies() return c.request.Cookies()
} }
func (c *echoContext) Set(key string, val interface{}) { func (c *context) Set(key string, val interface{}) {
c.context = context.WithValue(c.context, key, val) if c.store == nil {
c.store = make(store)
}
c.store[key] = val
} }
func (c *echoContext) Get(key string) interface{} { func (c *context) Get(key string) interface{} {
return c.context.Value(key) return c.store[key]
} }
func (c *echoContext) Bind(i interface{}) error { func (c *context) Bind(i interface{}) error {
return c.echo.Binder.Bind(i, c) return c.echo.Binder.Bind(i, c)
} }
func (c *echoContext) Render(code int, name string, data interface{}) (err error) { func (c *context) Render(code int, name string, data interface{}) (err error) {
if c.echo.Renderer == nil { if c.echo.Renderer == nil {
return ErrRendererNotRegistered return ErrRendererNotRegistered
} }
@ -409,21 +387,21 @@ func (c *echoContext) Render(code int, name string, data interface{}) (err error
return return
} }
func (c *echoContext) HTML(code int, html string) (err error) { func (c *context) HTML(code int, html string) (err error) {
c.response.Header().Set(HeaderContentType, MIMETextHTMLCharsetUTF8) c.response.Header().Set(HeaderContentType, MIMETextHTMLCharsetUTF8)
c.response.WriteHeader(code) c.response.WriteHeader(code)
_, err = c.response.Write([]byte(html)) _, err = c.response.Write([]byte(html))
return return
} }
func (c *echoContext) String(code int, s string) (err error) { func (c *context) String(code int, s string) (err error) {
c.response.Header().Set(HeaderContentType, MIMETextPlainCharsetUTF8) c.response.Header().Set(HeaderContentType, MIMETextPlainCharsetUTF8)
c.response.WriteHeader(code) c.response.WriteHeader(code)
_, err = c.response.Write([]byte(s)) _, err = c.response.Write([]byte(s))
return return
} }
func (c *echoContext) JSON(code int, i interface{}) (err error) { func (c *context) JSON(code int, i interface{}) (err error) {
b, err := json.Marshal(i) b, err := json.Marshal(i)
if c.echo.Debug { if c.echo.Debug {
b, err = json.MarshalIndent(i, "", " ") b, err = json.MarshalIndent(i, "", " ")
@ -434,11 +412,11 @@ func (c *echoContext) JSON(code int, i interface{}) (err error) {
return c.JSONBlob(code, b) return c.JSONBlob(code, b)
} }
func (c *echoContext) JSONBlob(code int, b []byte) (err error) { func (c *context) JSONBlob(code int, b []byte) (err error) {
return c.Blob(code, MIMEApplicationJSONCharsetUTF8, b) return c.Blob(code, MIMEApplicationJSONCharsetUTF8, b)
} }
func (c *echoContext) JSONP(code int, callback string, i interface{}) (err error) { func (c *context) JSONP(code int, callback string, i interface{}) (err error) {
b, err := json.Marshal(i) b, err := json.Marshal(i)
if err != nil { if err != nil {
return err return err
@ -446,7 +424,7 @@ func (c *echoContext) JSONP(code int, callback string, i interface{}) (err error
return c.JSONPBlob(code, callback, b) return c.JSONPBlob(code, callback, b)
} }
func (c *echoContext) JSONPBlob(code int, callback string, b []byte) (err error) { func (c *context) JSONPBlob(code int, callback string, b []byte) (err error) {
c.response.Header().Set(HeaderContentType, MIMEApplicationJavaScriptCharsetUTF8) c.response.Header().Set(HeaderContentType, MIMEApplicationJavaScriptCharsetUTF8)
c.response.WriteHeader(code) c.response.WriteHeader(code)
if _, err = c.response.Write([]byte(callback + "(")); err != nil { if _, err = c.response.Write([]byte(callback + "(")); err != nil {
@ -459,7 +437,7 @@ func (c *echoContext) JSONPBlob(code int, callback string, b []byte) (err error)
return return
} }
func (c *echoContext) XML(code int, i interface{}) (err error) { func (c *context) XML(code int, i interface{}) (err error) {
b, err := xml.Marshal(i) b, err := xml.Marshal(i)
if c.echo.Debug { if c.echo.Debug {
b, err = xml.MarshalIndent(i, "", " ") b, err = xml.MarshalIndent(i, "", " ")
@ -470,28 +448,28 @@ func (c *echoContext) XML(code int, i interface{}) (err error) {
return c.XMLBlob(code, b) return c.XMLBlob(code, b)
} }
func (c *echoContext) XMLBlob(code int, b []byte) (err error) { func (c *context) XMLBlob(code int, b []byte) (err error) {
if _, err = c.response.Write([]byte(xml.Header)); err != nil { if _, err = c.response.Write([]byte(xml.Header)); err != nil {
return return
} }
return c.Blob(code, MIMEApplicationXMLCharsetUTF8, b) return c.Blob(code, MIMEApplicationXMLCharsetUTF8, b)
} }
func (c *echoContext) Blob(code int, contentType string, b []byte) (err error) { func (c *context) Blob(code int, contentType string, b []byte) (err error) {
c.response.Header().Set(HeaderContentType, contentType) c.response.Header().Set(HeaderContentType, contentType)
c.response.WriteHeader(code) c.response.WriteHeader(code)
_, err = c.response.Write(b) _, err = c.response.Write(b)
return return
} }
func (c *echoContext) Stream(code int, contentType string, r io.Reader) (err error) { func (c *context) Stream(code int, contentType string, r io.Reader) (err error) {
c.response.Header().Set(HeaderContentType, contentType) c.response.Header().Set(HeaderContentType, contentType)
c.response.WriteHeader(code) c.response.WriteHeader(code)
_, err = io.Copy(c.response, r) _, err = io.Copy(c.response, r)
return return
} }
func (c *echoContext) File(file string) error { func (c *context) File(file string) error {
f, err := os.Open(file) f, err := os.Open(file)
if err != nil { if err != nil {
return ErrNotFound return ErrNotFound
@ -512,15 +490,15 @@ func (c *echoContext) File(file string) error {
return c.ServeContent(f, fi.Name(), fi.ModTime()) return c.ServeContent(f, fi.Name(), fi.ModTime())
} }
func (c *echoContext) Attachment(r io.ReadSeeker, name string) (err error) { func (c *context) Attachment(r io.ReadSeeker, name string) (err error) {
return c.contentDisposition(r, name, "attachment") return c.contentDisposition(r, name, "attachment")
} }
func (c *echoContext) Inline(r io.ReadSeeker, name string) (err error) { func (c *context) Inline(r io.ReadSeeker, name string) (err error) {
return c.contentDisposition(r, name, "inline") return c.contentDisposition(r, name, "inline")
} }
func (c *echoContext) contentDisposition(r io.ReadSeeker, name, dispositionType string) (err error) { func (c *context) contentDisposition(r io.ReadSeeker, name, dispositionType string) (err error) {
c.response.Header().Set(HeaderContentType, ContentTypeByExtension(name)) c.response.Header().Set(HeaderContentType, ContentTypeByExtension(name))
c.response.Header().Set(HeaderContentDisposition, fmt.Sprintf("%s; filename=%s", dispositionType, name)) c.response.Header().Set(HeaderContentDisposition, fmt.Sprintf("%s; filename=%s", dispositionType, name))
c.response.WriteHeader(http.StatusOK) c.response.WriteHeader(http.StatusOK)
@ -528,12 +506,12 @@ func (c *echoContext) contentDisposition(r io.ReadSeeker, name, dispositionType
return return
} }
func (c *echoContext) NoContent(code int) error { func (c *context) NoContent(code int) error {
c.response.WriteHeader(code) c.response.WriteHeader(code)
return nil return nil
} }
func (c *echoContext) Redirect(code int, url string) error { func (c *context) Redirect(code int, url string) error {
if code < http.StatusMultipleChoices || code > http.StatusTemporaryRedirect { if code < http.StatusMultipleChoices || code > http.StatusTemporaryRedirect {
return ErrInvalidRedirectCode return ErrInvalidRedirectCode
} }
@ -542,27 +520,27 @@ func (c *echoContext) Redirect(code int, url string) error {
return nil return nil
} }
func (c *echoContext) Error(err error) { func (c *context) Error(err error) {
c.echo.HTTPErrorHandler(err, c) c.echo.HTTPErrorHandler(err, c)
} }
func (c *echoContext) Echo() *Echo { func (c *context) Echo() *Echo {
return c.echo return c.echo
} }
func (c *echoContext) Handler() HandlerFunc { func (c *context) Handler() HandlerFunc {
return c.handler return c.handler
} }
func (c *echoContext) SetHandler(h HandlerFunc) { func (c *context) SetHandler(h HandlerFunc) {
c.handler = h c.handler = h
} }
func (c *echoContext) Logger() Logger { func (c *context) Logger() Logger {
return c.echo.Logger return c.echo.Logger
} }
func (c *echoContext) ServeContent(content io.ReadSeeker, name string, modtime time.Time) error { func (c *context) ServeContent(content io.ReadSeeker, name string, modtime time.Time) error {
req := c.Request() req := c.Request()
res := c.Response() res := c.Response()
@ -589,9 +567,9 @@ func ContentTypeByExtension(name string) (t string) {
return return
} }
func (c *echoContext) Reset(r *http.Request, w http.ResponseWriter) { func (c *context) Reset(r *http.Request, w http.ResponseWriter) {
// c.query = nil c.query = nil
c.context = context.Background() c.store = nil
c.request = r c.request = r
c.response.reset(w) c.response.reset(w)
c.handler = NotFoundHandler c.handler = NotFoundHandler

View File

@ -1,94 +0,0 @@
package context
import "time"
type Context interface {
// Deadline returns the time when work done on behalf of this context
// should be canceled. Deadline returns ok==false when no deadline is
// set. Successive calls to Deadline return the same results.
Deadline() (deadline time.Time, ok bool)
// Done returns a channel that's closed when work done on behalf of this
// context should be canceled. Done may return nil if this context can
// never be canceled. Successive calls to Done return the same value.
//
// WithCancel arranges for Done to be closed when cancel is called;
// WithDeadline arranges for Done to be closed when the deadline
// expires; WithTimeout arranges for Done to be closed when the timeout
// elapses.
//
// Done is provided for use in select statements:
//
// // Stream generates values with DoSomething and sends them to out
// // until DoSomething returns an error or ctx.Done is closed.
// func Stream(ctx context.Context, out chan<- Value) error {
// for {
// v, err := DoSomething(ctx)
// if err != nil {
// return err
// }
// select {
// case <-ctx.Done():
// return ctx.Err()
// case out <- v:
// }
// }
// }
//
// See https://blog.golang.org/pipelines for more examples of how to use
// a Done channel for cancelation.
Done() <-chan struct{}
// Err returns a non-nil error value after Done is closed. Err returns
// Canceled if the context was canceled or DeadlineExceeded if the
// context's deadline passed. No other values for Err are defined.
// After Done is closed, successive calls to Err return the same value.
Err() error
// Value returns the value associated with this context for key, or nil
// if no value is associated with key. Successive calls to Value with
// the same key returns the same result.
//
// Use context values only for request-scoped data that transits
// processes and API boundaries, not for passing optional parameters to
// functions.
//
// A key identifies a specific value in a Context. Functions that wish
// to store values in Context typically allocate a key in a global
// variable then use that key as the argument to context.WithValue and
// Context.Value. A key can be any type that supports equality;
// packages should define keys as an unexported type to avoid
// collisions.
//
// Packages that define a Context key should provide type-safe accessors
// for the values stored using that key:
//
// // Package user defines a User type that's stored in Contexts.
// package user
//
// import "context"
//
// // User is the type of value stored in the Contexts.
// type User struct {...}
//
// // key is an unexported type for keys defined in this package.
// // This prevents collisions with keys defined in other packages.
// type key int
//
// // userKey is the key for user.User values in Contexts. It is
// // unexported; clients use user.NewContext and user.FromContext
// // instead of using this key directly.
// var userKey key = 0
//
// // NewContext returns a new Context that carries value u.
// func NewContext(ctx context.Context, u *User) context.Context {
// return context.WithValue(ctx, userKey, u)
// }
//
// // FromContext returns the User value stored in ctx, if any.
// func FromContext(ctx context.Context) (*User, bool) {
// u, ok := ctx.Value(userKey).(*User)
// return u, ok
// }
Value(key interface{}) interface{}
}

View File

@ -1,13 +0,0 @@
// +build go1.7
package context
import "context"
func Background() Context {
return context.Background()
}
func WithValue(parent Context, key, val interface{}) Context {
return context.WithValue(parent, key, val)
}

View File

@ -1,13 +0,0 @@
// +build !go1.7
package context
import "golang.org/x/net/context"
func Background() Context {
return context.Background()
}
func WithValue(parent Context, key, val interface{}) Context {
return context.WithValue(parent, key, val)
}

View File

@ -12,8 +12,6 @@ import (
"text/template" "text/template"
"time" "time"
"golang.org/x/net/context"
"strings" "strings"
"net/url" "net/url"
@ -37,7 +35,7 @@ func TestContext(t *testing.T) {
e := New() e := New()
req, _ := http.NewRequest(POST, "/", strings.NewReader(userJSON)) req, _ := http.NewRequest(POST, "/", strings.NewReader(userJSON))
rec := httptest.NewRecorder() rec := httptest.NewRecorder()
c := e.NewContext(req, rec).(*echoContext) c := e.NewContext(req, rec).(*context)
// Echo // Echo
assert.Equal(t, e, c.Echo()) assert.Equal(t, e, c.Echo())
@ -68,7 +66,7 @@ func TestContext(t *testing.T) {
// JSON // JSON
rec = httptest.NewRecorder() rec = httptest.NewRecorder()
c = e.NewContext(req, rec).(*echoContext) c = e.NewContext(req, rec).(*context)
err = c.JSON(http.StatusOK, user{1, "Jon Snow"}) err = c.JSON(http.StatusOK, user{1, "Jon Snow"})
if assert.NoError(t, err) { if assert.NoError(t, err) {
assert.Equal(t, http.StatusOK, rec.Code) assert.Equal(t, http.StatusOK, rec.Code)
@ -78,13 +76,13 @@ func TestContext(t *testing.T) {
// JSON (error) // JSON (error)
rec = httptest.NewRecorder() rec = httptest.NewRecorder()
c = e.NewContext(req, rec).(*echoContext) c = e.NewContext(req, rec).(*context)
err = c.JSON(http.StatusOK, make(chan bool)) err = c.JSON(http.StatusOK, make(chan bool))
assert.Error(t, err) assert.Error(t, err)
// JSONP // JSONP
rec = httptest.NewRecorder() rec = httptest.NewRecorder()
c = e.NewContext(req, rec).(*echoContext) c = e.NewContext(req, rec).(*context)
callback := "callback" callback := "callback"
err = c.JSONP(http.StatusOK, callback, user{1, "Jon Snow"}) err = c.JSONP(http.StatusOK, callback, user{1, "Jon Snow"})
if assert.NoError(t, err) { if assert.NoError(t, err) {
@ -95,7 +93,7 @@ func TestContext(t *testing.T) {
// XML // XML
rec = httptest.NewRecorder() rec = httptest.NewRecorder()
c = e.NewContext(req, rec).(*echoContext) c = e.NewContext(req, rec).(*context)
err = c.XML(http.StatusOK, user{1, "Jon Snow"}) err = c.XML(http.StatusOK, user{1, "Jon Snow"})
if assert.NoError(t, err) { if assert.NoError(t, err) {
assert.Equal(t, http.StatusOK, rec.Code) assert.Equal(t, http.StatusOK, rec.Code)
@ -105,13 +103,13 @@ func TestContext(t *testing.T) {
// XML (error) // XML (error)
rec = httptest.NewRecorder() rec = httptest.NewRecorder()
c = e.NewContext(req, rec).(*echoContext) c = e.NewContext(req, rec).(*context)
err = c.XML(http.StatusOK, make(chan bool)) err = c.XML(http.StatusOK, make(chan bool))
assert.Error(t, err) assert.Error(t, err)
// String // String
rec = httptest.NewRecorder() rec = httptest.NewRecorder()
c = e.NewContext(req, rec).(*echoContext) c = e.NewContext(req, rec).(*context)
err = c.String(http.StatusOK, "Hello, World!") err = c.String(http.StatusOK, "Hello, World!")
if assert.NoError(t, err) { if assert.NoError(t, err) {
assert.Equal(t, http.StatusOK, rec.Code) assert.Equal(t, http.StatusOK, rec.Code)
@ -121,7 +119,7 @@ func TestContext(t *testing.T) {
// HTML // HTML
rec = httptest.NewRecorder() rec = httptest.NewRecorder()
c = e.NewContext(req, rec).(*echoContext) c = e.NewContext(req, rec).(*context)
err = c.HTML(http.StatusOK, "Hello, <strong>World!</strong>") err = c.HTML(http.StatusOK, "Hello, <strong>World!</strong>")
if assert.NoError(t, err) { if assert.NoError(t, err) {
assert.Equal(t, http.StatusOK, rec.Code) assert.Equal(t, http.StatusOK, rec.Code)
@ -131,7 +129,7 @@ func TestContext(t *testing.T) {
// Stream // Stream
rec = httptest.NewRecorder() rec = httptest.NewRecorder()
c = e.NewContext(req, rec).(*echoContext) c = e.NewContext(req, rec).(*context)
r := strings.NewReader("response from a stream") r := strings.NewReader("response from a stream")
err = c.Stream(http.StatusOK, "application/octet-stream", r) err = c.Stream(http.StatusOK, "application/octet-stream", r)
if assert.NoError(t, err) { if assert.NoError(t, err) {
@ -142,7 +140,7 @@ func TestContext(t *testing.T) {
// Attachment // Attachment
rec = httptest.NewRecorder() rec = httptest.NewRecorder()
c = e.NewContext(req, rec).(*echoContext) c = e.NewContext(req, rec).(*context)
file, err := os.Open("_fixture/images/walle.png") file, err := os.Open("_fixture/images/walle.png")
if assert.NoError(t, err) { if assert.NoError(t, err) {
err = c.Attachment(file, "walle.png") err = c.Attachment(file, "walle.png")
@ -155,7 +153,7 @@ func TestContext(t *testing.T) {
// Inline // Inline
rec = httptest.NewRecorder() rec = httptest.NewRecorder()
c = e.NewContext(req, rec).(*echoContext) c = e.NewContext(req, rec).(*context)
file, err = os.Open("_fixture/images/walle.png") file, err = os.Open("_fixture/images/walle.png")
if assert.NoError(t, err) { if assert.NoError(t, err) {
err = c.Inline(file, "walle.png") err = c.Inline(file, "walle.png")
@ -168,13 +166,13 @@ func TestContext(t *testing.T) {
// NoContent // NoContent
rec = httptest.NewRecorder() rec = httptest.NewRecorder()
c = e.NewContext(req, rec).(*echoContext) c = e.NewContext(req, rec).(*context)
c.NoContent(http.StatusOK) c.NoContent(http.StatusOK)
assert.Equal(t, http.StatusOK, rec.Code) assert.Equal(t, http.StatusOK, rec.Code)
// Error // Error
rec = httptest.NewRecorder() rec = httptest.NewRecorder()
c = e.NewContext(req, rec).(*echoContext) c = e.NewContext(req, rec).(*context)
c.Error(errors.New("error")) c.Error(errors.New("error"))
assert.Equal(t, http.StatusInternalServerError, rec.Code) assert.Equal(t, http.StatusInternalServerError, rec.Code)
@ -190,7 +188,7 @@ func TestContextCookie(t *testing.T) {
req.Header.Add(HeaderCookie, theme) req.Header.Add(HeaderCookie, theme)
req.Header.Add(HeaderCookie, user) req.Header.Add(HeaderCookie, user)
rec := httptest.NewRecorder() rec := httptest.NewRecorder()
c := e.NewContext(req, rec).(*echoContext) c := e.NewContext(req, rec).(*context)
// Read single // Read single
cookie, err := c.Cookie("theme") cookie, err := c.Cookie("theme")
@ -351,23 +349,9 @@ func TestContextRedirect(t *testing.T) {
assert.Error(t, c.Redirect(310, "http://labstack.github.io/echo")) assert.Error(t, c.Redirect(310, "http://labstack.github.io/echo"))
} }
func TestContextEmbedded(t *testing.T) {
var c Context
c = new(echoContext)
c.SetStdContext(context.WithValue(c, "key", "val"))
assert.Equal(t, "val", c.Value("key"))
now := time.Now()
ctx, _ := context.WithDeadline(context.Background(), now)
c.SetStdContext(ctx)
n, _ := ctx.Deadline()
assert.Equal(t, now, n)
assert.Equal(t, context.DeadlineExceeded, c.Err())
assert.NotNil(t, c.Done())
}
func TestContextStore(t *testing.T) { func TestContextStore(t *testing.T) {
var c Context var c Context
c = new(echoContext) c = new(context)
c.Set("name", "Jon Snow") c.Set("name", "Jon Snow")
assert.Equal(t, "Jon Snow", c.Get("name")) assert.Equal(t, "Jon Snow", c.Get("name"))
} }

View File

@ -53,7 +53,6 @@ import (
"github.com/rsc/letsencrypt" "github.com/rsc/letsencrypt"
"golang.org/x/net/context"
"golang.org/x/net/websocket" "golang.org/x/net/websocket"
"github.com/labstack/gommon/color" "github.com/labstack/gommon/color"
@ -263,10 +262,10 @@ func New() (e *Echo) {
// NewContext returns a Context instance. // NewContext returns a Context instance.
func (e *Echo) NewContext(r *http.Request, w http.ResponseWriter) Context { func (e *Echo) NewContext(r *http.Request, w http.ResponseWriter) Context {
return &echoContext{ return &context{
context: context.Background(),
request: r, request: r,
response: NewResponse(w, e), response: NewResponse(w, e),
store: make(store),
echo: e, echo: e,
pvalues: make([]string, *e.maxParam), pvalues: make([]string, *e.maxParam),
handler: NotFoundHandler, handler: NotFoundHandler,
@ -486,7 +485,7 @@ func (e *Echo) ReleaseContext(c Context) {
// ServeHTTP implements `http.Handler` interface, which serves HTTP requests. // ServeHTTP implements `http.Handler` interface, which serves HTTP requests.
func (e *Echo) ServeHTTP(w http.ResponseWriter, r *http.Request) { func (e *Echo) ServeHTTP(w http.ResponseWriter, r *http.Request) {
c := e.pool.Get().(*echoContext) c := e.pool.Get().(*context)
c.Reset(r, w) c.Reset(r, w)
// Middleware // Middleware

View File

@ -404,7 +404,7 @@ func TestEchoHTTPError(t *testing.T) {
func TestEchoContext(t *testing.T) { func TestEchoContext(t *testing.T) {
e := New() e := New()
c := e.AcquireContext() c := e.AcquireContext()
assert.IsType(t, new(echoContext), c) assert.IsType(t, new(context), c)
e.ReleaseContext(c) e.ReleaseContext(c)
} }

View File

@ -281,7 +281,7 @@ func TestRouterStatic(t *testing.T) {
c.Set("path", path) c.Set("path", path)
return nil return nil
}, e) }, e)
c := e.NewContext(nil, nil).(*echoContext) c := e.NewContext(nil, nil).(*context)
r.Find(GET, path, c) r.Find(GET, path, c)
c.handler(c) c.handler(c)
assert.Equal(t, path, c.Get("path")) assert.Equal(t, path, c.Get("path"))
@ -293,7 +293,7 @@ func TestRouterParam(t *testing.T) {
r.Add(GET, "/users/:id", func(c Context) error { r.Add(GET, "/users/:id", func(c Context) error {
return nil return nil
}, e) }, e)
c := e.NewContext(nil, nil).(*echoContext) c := e.NewContext(nil, nil).(*context)
r.Find(GET, "/users/1", c) r.Find(GET, "/users/1", c)
assert.Equal(t, "1", c.P(0)) assert.Equal(t, "1", c.P(0))
} }
@ -304,7 +304,7 @@ func TestRouterTwoParam(t *testing.T) {
r.Add(GET, "/users/:uid/files/:fid", func(Context) error { r.Add(GET, "/users/:uid/files/:fid", func(Context) error {
return nil return nil
}, e) }, e)
c := e.NewContext(nil, nil).(*echoContext) c := e.NewContext(nil, nil).(*context)
r.Find(GET, "/users/1/files/1", c) r.Find(GET, "/users/1/files/1", c)
assert.Equal(t, "1", c.P(0)) assert.Equal(t, "1", c.P(0))
@ -324,7 +324,7 @@ func TestRouterParamWithSlash(t *testing.T) {
return nil return nil
}, e) }, e)
c := e.NewContext(nil, nil).(*echoContext) c := e.NewContext(nil, nil).(*context)
assert.NotPanics(t, func() { assert.NotPanics(t, func() {
r.Find(GET, "/a/1/c/d/2/3", c) r.Find(GET, "/a/1/c/d/2/3", c)
}) })
@ -344,7 +344,7 @@ func TestRouterMatchAny(t *testing.T) {
r.Add(GET, "/users/*", func(Context) error { r.Add(GET, "/users/*", func(Context) error {
return nil return nil
}, e) }, e)
c := e.NewContext(nil, nil).(*echoContext) c := e.NewContext(nil, nil).(*context)
r.Find(GET, "/", c) r.Find(GET, "/", c)
assert.Equal(t, "", c.P(0)) assert.Equal(t, "", c.P(0))
@ -362,7 +362,7 @@ func TestRouterMicroParam(t *testing.T) {
r.Add(GET, "/:a/:b/:c", func(c Context) error { r.Add(GET, "/:a/:b/:c", func(c Context) error {
return nil return nil
}, e) }, e)
c := e.NewContext(nil, nil).(*echoContext) c := e.NewContext(nil, nil).(*context)
r.Find(GET, "/1/2/3", c) r.Find(GET, "/1/2/3", c)
assert.Equal(t, "1", c.P(0)) assert.Equal(t, "1", c.P(0))
assert.Equal(t, "2", c.P(1)) assert.Equal(t, "2", c.P(1))
@ -377,7 +377,7 @@ func TestRouterMixParamMatchAny(t *testing.T) {
r.Add(GET, "/users/:id/*", func(c Context) error { r.Add(GET, "/users/:id/*", func(c Context) error {
return nil return nil
}, e) }, e)
c := e.NewContext(nil, nil).(*echoContext) c := e.NewContext(nil, nil).(*context)
r.Find(GET, "/users/joe/comments", c) r.Find(GET, "/users/joe/comments", c)
c.handler(c) c.handler(c)
@ -396,7 +396,7 @@ func TestRouterMultiRoute(t *testing.T) {
r.Add(GET, "/users/:id", func(c Context) error { r.Add(GET, "/users/:id", func(c Context) error {
return nil return nil
}, e) }, e)
c := e.NewContext(nil, nil).(*echoContext) c := e.NewContext(nil, nil).(*context)
// Route > /users // Route > /users
r.Find(GET, "/users", c) r.Find(GET, "/users", c)
@ -408,7 +408,7 @@ func TestRouterMultiRoute(t *testing.T) {
assert.Equal(t, "1", c.P(0)) assert.Equal(t, "1", c.P(0))
// Route > /user // Route > /user
c = e.NewContext(nil, nil).(*echoContext) c = e.NewContext(nil, nil).(*context)
r.Find(GET, "/user", c) r.Find(GET, "/user", c)
he := c.handler(c).(*HTTPError) he := c.handler(c).(*HTTPError)
assert.Equal(t, http.StatusNotFound, he.Code) assert.Equal(t, http.StatusNotFound, he.Code)
@ -447,7 +447,7 @@ func TestRouterPriority(t *testing.T) {
c.Set("g", 7) c.Set("g", 7)
return nil return nil
}, e) }, e)
c := e.NewContext(nil, nil).(*echoContext) c := e.NewContext(nil, nil).(*context)
// Route > /users // Route > /users
r.Find(GET, "/users", c) r.Find(GET, "/users", c)
@ -490,7 +490,7 @@ func TestRouterPriority(t *testing.T) {
func TestRouterPriorityNotFound(t *testing.T) { func TestRouterPriorityNotFound(t *testing.T) {
e := New() e := New()
r := e.router r := e.router
c := e.NewContext(nil, nil).(*echoContext) c := e.NewContext(nil, nil).(*context)
// Add // Add
r.Add(GET, "/a/foo", func(c Context) error { r.Add(GET, "/a/foo", func(c Context) error {
@ -511,7 +511,7 @@ func TestRouterPriorityNotFound(t *testing.T) {
c.handler(c) c.handler(c)
assert.Equal(t, 2, c.Get("b")) assert.Equal(t, 2, c.Get("b"))
c = e.NewContext(nil, nil).(*echoContext) c = e.NewContext(nil, nil).(*context)
r.Find(GET, "/abc/def", c) r.Find(GET, "/abc/def", c)
he := c.handler(c).(*HTTPError) he := c.handler(c).(*HTTPError)
assert.Equal(t, http.StatusNotFound, he.Code) assert.Equal(t, http.StatusNotFound, he.Code)
@ -532,7 +532,7 @@ func TestRouterParamNames(t *testing.T) {
r.Add(GET, "/users/:uid/files/:fid", func(c Context) error { r.Add(GET, "/users/:uid/files/:fid", func(c Context) error {
return nil return nil
}, e) }, e)
c := e.NewContext(nil, nil).(*echoContext) c := e.NewContext(nil, nil).(*context)
// Route > /users // Route > /users
r.Find(GET, "/users", c) r.Find(GET, "/users", c)
@ -561,7 +561,7 @@ func TestRouterAPI(t *testing.T) {
return nil return nil
}, e) }, e)
} }
c := e.NewContext(nil, nil).(*echoContext) c := e.NewContext(nil, nil).(*context)
for _, route := range api { for _, route := range api {
r.Find(route.Method, route.Path, c) r.Find(route.Method, route.Path, c)
for i, n := range c.pnames { for i, n := range c.pnames {