Skip to content

Commit bf85c56

Browse files
committed
Encapsulated fields and exposed public functions.
Signed-off-by: Vishal Rana <vr@labstack.com>
1 parent df924ff commit bf85c56

File tree

13 files changed

+108
-82
lines changed

13 files changed

+108
-82
lines changed

context.go

Lines changed: 37 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -11,9 +11,9 @@ type (
1111
// Context represents context for the current request. It holds request and
1212
// response objects, path parameters, data and registered handler.
1313
Context struct {
14-
Request *http.Request
15-
Response *Response
16-
Socket *websocket.Conn
14+
request *http.Request
15+
response *Response
16+
socket *websocket.Conn
1717
pnames []string
1818
pvalues []string
1919
store store
@@ -24,15 +24,30 @@ type (
2424

2525
func NewContext(req *http.Request, res *Response, e *Echo) *Context {
2626
return &Context{
27-
Request: req,
28-
Response: res,
27+
request: req,
28+
response: res,
2929
echo: e,
3030
pnames: make([]string, e.maxParam),
3131
pvalues: make([]string, e.maxParam),
3232
store: make(store),
3333
}
3434
}
3535

36+
// Request returns *http.Request.
37+
func (c *Context) Request() *http.Request {
38+
return c.request
39+
}
40+
41+
// Response returns *Response.
42+
func (c *Context) Response() *Response {
43+
return c.response
44+
}
45+
46+
// Socket returns *websocket.Conn.
47+
func (c *Context) Socket() *websocket.Conn {
48+
return c.socket
49+
}
50+
3651
// P returns path parameter by index.
3752
func (c *Context) P(i uint8) (value string) {
3853
l := uint8(len(c.pnames))
@@ -57,7 +72,7 @@ func (c *Context) Param(name string) (value string) {
5772
// Bind binds the request body into specified type v. Default binder does it
5873
// based on Content-Type header.
5974
func (c *Context) Bind(i interface{}) error {
60-
return c.echo.binder(c.Request, i)
75+
return c.echo.binder(c.request, i)
6176
}
6277

6378
// Render invokes the registered HTML template renderer and sends a text/html
@@ -66,37 +81,37 @@ func (c *Context) Render(code int, name string, data interface{}) error {
6681
if c.echo.renderer == nil {
6782
return RendererNotRegistered
6883
}
69-
c.Response.Header().Set(ContentType, TextHTML+"; charset=utf-8")
70-
c.Response.WriteHeader(code)
71-
return c.echo.renderer.Render(c.Response, name, data)
84+
c.response.Header().Set(ContentType, TextHTML+"; charset=utf-8")
85+
c.response.WriteHeader(code)
86+
return c.echo.renderer.Render(c.response, name, data)
7287
}
7388

7489
// JSON sends an application/json response with status code.
7590
func (c *Context) JSON(code int, i interface{}) error {
76-
c.Response.Header().Set(ContentType, ApplicationJSON+"; charset=utf-8")
77-
c.Response.WriteHeader(code)
78-
return json.NewEncoder(c.Response).Encode(i)
91+
c.response.Header().Set(ContentType, ApplicationJSON+"; charset=utf-8")
92+
c.response.WriteHeader(code)
93+
return json.NewEncoder(c.response).Encode(i)
7994
}
8095

8196
// String sends a text/plain response with status code.
8297
func (c *Context) String(code int, s string) error {
83-
c.Response.Header().Set(ContentType, TextPlain+"; charset=utf-8")
84-
c.Response.WriteHeader(code)
85-
_, err := c.Response.Write([]byte(s))
98+
c.response.Header().Set(ContentType, TextPlain+"; charset=utf-8")
99+
c.response.WriteHeader(code)
100+
_, err := c.response.Write([]byte(s))
86101
return err
87102
}
88103

89104
// HTML sends a text/html response with status code.
90105
func (c *Context) HTML(code int, html string) error {
91-
c.Response.Header().Set(ContentType, TextHTML+"; charset=utf-8")
92-
c.Response.WriteHeader(code)
93-
_, err := c.Response.Write([]byte(html))
106+
c.response.Header().Set(ContentType, TextHTML+"; charset=utf-8")
107+
c.response.WriteHeader(code)
108+
_, err := c.response.Write([]byte(html))
94109
return err
95110
}
96111

97112
// NoContent sends a response with no body and a status code.
98113
func (c *Context) NoContent(code int) error {
99-
c.Response.WriteHeader(code)
114+
c.response.WriteHeader(code)
100115
return nil
101116
}
102117

@@ -117,11 +132,11 @@ func (c *Context) Set(key string, val interface{}) {
117132

118133
// Redirect redirects the request using http.Redirect with status code.
119134
func (c *Context) Redirect(code int, url string) {
120-
http.Redirect(c.Response, c.Request, url, code)
135+
http.Redirect(c.response, c.request, url, code)
121136
}
122137

123138
func (c *Context) reset(w http.ResponseWriter, r *http.Request, e *Echo) {
124-
c.Request = r
125-
c.Response.reset(w)
139+
c.request = r
140+
c.response.reset(w)
126141
c.echo = e
127142
}

context_test.go

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -91,26 +91,26 @@ func TestContext(t *testing.T) {
9191

9292
// JSON
9393
r.Header.Set(Accept, ApplicationJSON)
94-
c.Response.committed = false
94+
c.response.committed = false
9595
if he := c.JSON(http.StatusOK, u1); he != nil {
9696
t.Errorf("json %#v", he)
9797
}
9898

9999
// String
100100
r.Header.Set(Accept, TextPlain)
101-
c.Response.committed = false
101+
c.response.committed = false
102102
if he := c.String(http.StatusOK, "Hello, World!"); he != nil {
103103
t.Errorf("string %#v", he.Error)
104104
}
105105

106106
// HTML
107107
r.Header.Set(Accept, TextHTML)
108-
c.Response.committed = false
108+
c.response.committed = false
109109
if he := c.HTML(http.StatusOK, "Hello, <strong>World!</strong>"); he != nil {
110110
t.Errorf("html %v", he.Error)
111111
}
112112

113113
// Redirect
114-
c.Response.committed = false
114+
c.response.committed = false
115115
c.Redirect(http.StatusMovedPermanently, "http://labstack.github.io/echo")
116116
}

echo.go

Lines changed: 32 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -13,9 +13,9 @@ import (
1313
"strings"
1414
"sync"
1515

16+
"github.com/bradfitz/http2"
1617
"github.com/mattn/go-colorable"
1718
"golang.org/x/net/websocket"
18-
"github.com/bradfitz/http2"
1919
)
2020

2121
type (
@@ -34,8 +34,8 @@ type (
3434
debug bool
3535
}
3636
HTTPError struct {
37-
Code int
38-
Message string
37+
code int
38+
message string
3939
}
4040
Middleware interface{}
4141
MiddlewareFunc func(HandlerFunc) HandlerFunc
@@ -123,15 +123,21 @@ var (
123123
)
124124

125125
func NewHTTPError(code int, msg ...string) *HTTPError {
126-
he := &HTTPError{Code: code, Message: http.StatusText(code)}
126+
he := &HTTPError{code: code, message: http.StatusText(code)}
127127
for _, m := range msg {
128-
he.Message = m
128+
he.message = m
129129
}
130130
return he
131131
}
132132

133+
// Code returns code.
134+
func (e *HTTPError) Code() int {
135+
return e.code
136+
}
137+
138+
// Error returns message.
133139
func (e *HTTPError) Error() string {
134-
return e.Message
140+
return e.message
135141
}
136142

137143
// New creates an Echo instance.
@@ -157,13 +163,13 @@ func New() (e *Echo) {
157163
code := http.StatusInternalServerError
158164
msg := http.StatusText(code)
159165
if he, ok := err.(*HTTPError); ok {
160-
code = he.Code
161-
msg = he.Message
166+
code = he.code
167+
msg = he.message
162168
}
163169
if e.Debug() {
164170
msg = err.Error()
165171
}
166-
http.Error(c.Response, msg, code)
172+
http.Error(c.response, msg, code)
167173
})
168174
e.SetBinder(func(r *http.Request, v interface{}) error {
169175
ct := r.Header.Get(ContentType)
@@ -283,12 +289,12 @@ func (e *Echo) WebSocket(path string, h HandlerFunc) {
283289
e.Get(path, func(c *Context) (err error) {
284290
wss := websocket.Server{
285291
Handler: func(ws *websocket.Conn) {
286-
c.Socket = ws
287-
c.Response.status = http.StatusSwitchingProtocols
292+
c.socket = ws
293+
c.response.status = http.StatusSwitchingProtocols
288294
err = h(c)
289295
},
290296
}
291-
wss.ServeHTTP(c.Response.writer, c.Request)
297+
wss.ServeHTTP(c.response.writer, c.request)
292298
return err
293299
})
294300
}
@@ -313,15 +319,15 @@ func (e *Echo) Favicon(file string) {
313319
func (e *Echo) Static(path, root string) {
314320
fs := http.StripPrefix(path, http.FileServer(http.Dir(root)))
315321
e.Get(path+"*", func(c *Context) error {
316-
fs.ServeHTTP(c.Response, c.Request)
322+
fs.ServeHTTP(c.response, c.request)
317323
return nil
318324
})
319325
}
320326

321327
// ServeFile serves a file.
322328
func (e *Echo) ServeFile(path, file string) {
323329
e.Get(path, func(c *Context) error {
324-
http.ServeFile(c.Response, c.Request, file)
330+
http.ServeFile(c.response, c.request, file)
325331
return nil
326332
})
327333
}
@@ -399,17 +405,17 @@ func (e *Echo) RunTLSServer(srv *http.Server, certFile, keyFile string) {
399405
e.run(srv, certFile, keyFile)
400406
}
401407

402-
func (e *Echo) run(s *http.Server, f ...string) {
408+
func (e *Echo) run(s *http.Server, files ...string) {
403409
s.Handler = e
404410
if e.http2 {
405411
http2.ConfigureServer(s, nil)
406412
}
407-
if len(f) == 0 {
413+
if len(files) == 0 {
408414
log.Fatal(s.ListenAndServe())
409-
} else if len(f) == 2 {
410-
log.Fatal(s.ListenAndServeTLS(f[0], f[1]))
415+
} else if len(files) == 2 {
416+
log.Fatal(s.ListenAndServeTLS(files[0], files[1]))
411417
} else {
412-
log.Fatal("echo: invalid TLS configuration")
418+
log.Fatal("echo => invalid TLS configuration")
413419
}
414420
}
415421

@@ -428,10 +434,10 @@ func wrapMiddleware(m Middleware) MiddlewareFunc {
428434
return func(h HandlerFunc) HandlerFunc {
429435
return func(c *Context) (err error) {
430436
m(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
431-
c.Response.writer = w
432-
c.Request = r
437+
c.response.writer = w
438+
c.request = r
433439
err = h(c)
434-
})).ServeHTTP(c.Response.writer, c.Request)
440+
})).ServeHTTP(c.response.writer, c.request)
435441
return
436442
}
437443
}
@@ -462,8 +468,8 @@ func wrapHandlerFuncMW(m HandlerFunc) MiddlewareFunc {
462468
func wrapHTTPHandlerFuncMW(m http.HandlerFunc) MiddlewareFunc {
463469
return func(h HandlerFunc) HandlerFunc {
464470
return func(c *Context) error {
465-
if !c.Response.committed {
466-
m.ServeHTTP(c.Response.writer, c.Request)
471+
if !c.response.committed {
472+
m.ServeHTTP(c.response.writer, c.request)
467473
}
468474
return h(c)
469475
}
@@ -479,12 +485,12 @@ func wrapHandler(h Handler) HandlerFunc {
479485
return h
480486
case http.Handler, http.HandlerFunc:
481487
return func(c *Context) error {
482-
h.(http.Handler).ServeHTTP(c.Response, c.Request)
488+
h.(http.Handler).ServeHTTP(c.response, c.request)
483489
return nil
484490
}
485491
case func(http.ResponseWriter, *http.Request):
486492
return func(c *Context) error {
487-
h(c.Response, c.Request)
493+
h(c.response, c.request)
488494
return nil
489495
}
490496
default:

echo_test.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -252,7 +252,7 @@ func TestEchoMethod(t *testing.T) {
252252
func TestWebSocket(t *testing.T) {
253253
e := New()
254254
e.WebSocket("/ws", func(c *Context) error {
255-
c.Socket.Write([]byte("test"))
255+
c.socket.Write([]byte("test"))
256256
return nil
257257
})
258258
srv := httptest.NewServer(e)

middleware/auth.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ const (
2121
// For invalid credentials, it sends "401 - Unauthorized" response.
2222
func BasicAuth(fn AuthFunc) echo.HandlerFunc {
2323
return func(c *echo.Context) error {
24-
auth := c.Request.Header.Get(echo.Authorization)
24+
auth := c.Request().Header.Get(echo.Authorization)
2525
i := 0
2626
code := http.StatusBadRequest
2727

middleware/auth_test.go

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -48,8 +48,8 @@ func TestBasicAuth(t *testing.T) {
4848
he := ba(c).(*echo.HTTPError)
4949
if ba(c) == nil {
5050
t.Error("expected `fail`, with incorrect password.")
51-
} else if he.Code != http.StatusUnauthorized {
52-
t.Errorf("expected status `401`, got %d", he.Code)
51+
} else if he.Code() != http.StatusUnauthorized {
52+
t.Errorf("expected status `401`, got %d", he.Code())
5353
}
5454

5555
// Empty Authorization header
@@ -58,8 +58,8 @@ func TestBasicAuth(t *testing.T) {
5858
he = ba(c).(*echo.HTTPError)
5959
if he == nil {
6060
t.Error("expected `fail`, with empty Authorization header.")
61-
} else if he.Code != http.StatusBadRequest {
62-
t.Errorf("expected status `400`, got %d", he.Code)
61+
} else if he.Code() != http.StatusBadRequest {
62+
t.Errorf("expected status `400`, got %d", he.Code())
6363
}
6464

6565
// Invalid Authorization header
@@ -69,8 +69,8 @@ func TestBasicAuth(t *testing.T) {
6969
he = ba(c).(*echo.HTTPError)
7070
if he == nil {
7171
t.Error("expected `fail`, with invalid Authorization header.")
72-
} else if he.Code != http.StatusBadRequest {
73-
t.Errorf("expected status `400`, got %d", he.Code)
72+
} else if he.Code() != http.StatusBadRequest {
73+
t.Errorf("expected status `400`, got %d", he.Code())
7474
}
7575

7676
// Invalid scheme
@@ -80,7 +80,7 @@ func TestBasicAuth(t *testing.T) {
8080
he = ba(c).(*echo.HTTPError)
8181
if he == nil {
8282
t.Error("expected `fail`, with invalid scheme.")
83-
} else if he.Code != http.StatusBadRequest {
84-
t.Errorf("expected status `400`, got %d", he.Code)
83+
} else if he.Code() != http.StatusBadRequest {
84+
t.Errorf("expected status `400`, got %d", he.Code())
8585
}
8686
}

0 commit comments

Comments
 (0)