1
0
mirror of https://github.com/labstack/echo.git synced 2025-10-30 23:57:38 +02:00

Added errors

Signed-off-by: Vishal Rana <vr@labstack.com>
This commit is contained in:
Vishal Rana
2015-04-02 20:18:34 -07:00
parent 9d64eb9b86
commit 92e7a6c72c
4 changed files with 28 additions and 16 deletions

View File

@@ -16,7 +16,7 @@ Echo is a fast HTTP router (zero memory allocation) + micro web framework in Go.
- `http.Handler`
- `http.HandlerFunc`
- `func(http.ResponseWriter, *http.Request)`
- Sub/Group router
- Sub/Group routing
- Handy encoding/decoding functions.
- Serve static files, including index.
@@ -56,10 +56,14 @@ func init() {
func createUser(c *echo.Context) {
u := new(user)
if c.Bind(u) {
if err := c.Bind(u); err == nil {
users[u.ID] = *u
c.JSON(http.StatusCreated, u)
if err := c.JSON(http.StatusCreated, u); err == nil {
// Do something!
}
return
}
http.Error(c.Response, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
}
func getUsers(c *echo.Context) {

View File

@@ -31,20 +31,17 @@ func (c *Context) Param(n string) string {
}
// Bind decodes the payload into provided type based on Content-Type header.
func (c *Context) Bind(i interface{}) bool {
var err error
func (c *Context) Bind(i interface{}) (err error) {
ct := c.Request.Header.Get(HeaderContentType)
if strings.HasPrefix(ct, MIMEJSON) {
dec := json.NewDecoder(c.Request.Body)
err = dec.Decode(i)
if err = dec.Decode(i); err != nil {
err = ErrBindJSON
}
} else {
// TODO:
err = ErrUnsupportedContentType
}
if err != nil {
c.echo.internalServerErrorHandler(c)
return false
}
return true
return
}
// String sends a text/plain response with status code.
@@ -55,13 +52,14 @@ func (c *Context) String(n int, s string) {
}
// JSON sends an application/json response with status code.
func (c *Context) JSON(n int, i interface{}) {
func (c *Context) JSON(n int, i interface{}) (err error) {
enc := json.NewEncoder(c.Response)
c.Response.Header().Set(HeaderContentType, MIMEJSON+"; charset=utf-8")
c.Response.WriteHeader(n)
if err := enc.Encode(i); err != nil {
c.echo.internalServerErrorHandler(c)
err = ErrRenderJSON
}
return
}
// func (c *Context) File(n int, file, name string) {

View File

@@ -1,6 +1,7 @@
package echo
import (
"errors"
"log"
"net/http"
"sync"
@@ -55,6 +56,11 @@ var (
MethodPUT,
MethodTRACE,
}
// Errors
ErrUnsupportedContentType = errors.New("echo: unsupported content type")
ErrBindJSON = errors.New("echo: bind json error")
ErrRenderJSON = errors.New("echo: render json error")
)
// New creates a echo instance.

View File

@@ -27,10 +27,14 @@ func init() {
func createUser(c *echo.Context) {
u := new(user)
if c.Bind(u) {
if err := c.Bind(u); err == nil {
users[u.ID] = *u
c.JSON(http.StatusCreated, u)
if err := c.JSON(http.StatusCreated, u); err == nil {
// Do something!
}
return
}
http.Error(c.Response, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
}
func getUsers(c *echo.Context) {