1
0
mirror of https://github.com/labstack/echo.git synced 2025-09-16 09:16:29 +02:00

Updated README.md

Signed-off-by: Vishal Rana <vr@labstack.com>
This commit is contained in:
Vishal Rana
2016-04-02 19:32:52 -07:00
parent b5d6c05101
commit bcbd9a0f42
4 changed files with 202 additions and 39 deletions

205
README.md
View File

@@ -1,7 +1,7 @@
# *NOTICE*
- Master branch, website and godoc now points to Echo v2.
- It is advisable to migrate to v2. (https://labstack.com/echo/guide/migrating)
- It is advisable to migrate to v2. (https://labstack.com/echo/guide/migrating/)
- Looking for v1?
- Installation: Use a package manager (https://github.com/Masterminds/glide, it's nice!) to get stable v1 release/commit or use `go get gopkg.in/labstack/echo.v1`.
- Godoc: https://godoc.org/gopkg.in/labstack/echo.v1
@@ -9,25 +9,34 @@
# [Echo](http://labstack.com/echo) [![GoDoc](http://img.shields.io/badge/go-documentation-blue.svg?style=flat-square)](http://godoc.org/github.com/labstack/echo) [![License](http://img.shields.io/badge/license-mit-blue.svg?style=flat-square)](https://raw.githubusercontent.com/labstack/echo/master/LICENSE) [![Build Status](http://img.shields.io/travis/labstack/echo.svg?style=flat-square)](https://travis-ci.org/labstack/echo) [![Coverage Status](http://img.shields.io/coveralls/labstack/echo.svg?style=flat-square)](https://coveralls.io/r/labstack/echo) [![Join the chat at https://gitter.im/labstack/echo](https://img.shields.io/badge/gitter-join%20chat-brightgreen.svg?style=flat-square)](https://gitter.im/labstack/echo)
**A fast and unfancy micro web framework for Go.**
#### Echo is a fast and unfancy web framework for Go (Golang). Up to 10x faster than the rest.
## Features
- Fast HTTP router which smartly prioritize routes.
- Optimized HTTP router which smartly prioritize routes.
- Build robust and scalable RESTful APIs.
- Run with standard HTTP server or FastHTTP server.
- Group APIs.
- Extensible middleware framework.
- Router groups with nesting.
- Define middleware at root, group or route level.
- Handy functions to send variety of HTTP responses.
- Centralized HTTP error handling.
- Template rendering with any template engine.
- Define your format for the logger.
- Highly customizable.
## Performance
Based on [vishr/go-http-routing-benchmark] (https://github.com/vishr/go-http-routing-benchmark), June 5, 2015.
- Environment:
- Go 1.6
- wrk 4.0.0
- 2 GB, 2 Core (DigitalOcean)
- Test Suite: https://github.com/vishr/web-framework-benchmark
- Date: 4/4/2016
![Performance](http://i.imgur.com/hB2qdRS.png)
![Performance](http://i.imgur.com/fZVnK52.png)
## Getting Started
## Quick Start
### Installation
@@ -37,7 +46,7 @@ $ go get github.com/labstack/echo/...
### Hello, World!
Create `main.go`
Create `server.go`
```go
package main
@@ -46,48 +55,192 @@ import (
"net/http"
"github.com/labstack/echo"
"github.com/labstack/echo/engine/standard"
"github.com/labstack/echo/middleware"
)
func main() {
// Echo instance
e := echo.New()
// Middleware
e.Use(middleware.Logger())
e.Use(middleware.Recover())
// Route => handler
e.Get("/", func(c echo.Context) error {
return c.String(http.StatusOK, "Hello, World!\n")
e.Get("/hello", func(c echo.Context) error {
return c.String(http.StatusOK, "Hello, World!")
})
// Start server
e.Run(standard.New(":1323"))
}
```
Start server
```sh
$ go run main.go
$ go run server.go
```
Browse to [http://localhost:1323](http://localhost:1323) and you should see
Hello, World! on the page.
### Routing
```go
e.Post("/users", saveUser)
e.Get("/users/:id", getUser)
e.Put("/users/:id", updateUser)
e.Delete("/users/:id", deleteUser)
```
### Path Parameters
```go
func getUser(c echo.Context) error {
// User ID from path `users/:id`
id := c.Param("id")
}
```
### Query Parameters
`/show?team=x-men&member=wolverine`
```go
func show(c echo.Context) error {
// Get team and member from the query string
team := c.QueryParam("team")
member := c.QueryParam("team")
}
```
### Form `application/x-www-form-urlencoded`
`POST` `/save` `name=Joe Smith, email=joe@labstack.com`
name | value
:--- | :---
name | Joe Smith
email | joe@labstack.com
```go
func save(c echo.Context) error {
// Get name and email
name := c.FormValue("name")
email := c.FormParam("email")
}
```
### Form `multipart/form-data`
`POST` `/save`
name | value
:--- | :---
name | Joe Smith
email | joe@labstack.com
avatar | avatar
```go
func save(c echo.Context) error {
// Get name and email
name := c.FormValue("name")
email := c.FormParam("email")
//------------
// Get avatar
//------------
avatar, err := c.FormFile("avatar")
if err != nil {
return err
}
src, err := file.Open()
if err != nil {
return err
}
defer src.Close()
// Destination
file, err := os.Create(file.Filename)
if err != nil {
return err
}
defer file.Close()
// Copy
if _, err = io.Copy(file, avatar); err != nil {
return err
}
}
```
### Handling Request
- Bind `JSON` or `XML` payload into Go struct based on `Content-Type` request header.
- Render response as `JSON` or `XML` with status code.
```go
type User struct {
Name string `json:"name" xml:"name"`
Email string `json:"email" xml:"email"`
}
e.Post("/users", func(c echo.Context) error {
u := new(User)
if err := c.Bind(u); err != nil {
return err
}
return c.JSON(http.StatusCreated, u)
// or
// return c.XML(http.StatusCreated, u)
})
```
### Static Content
Server any file from static directory for path `/static/*`.
```go
e.Static("/static", "static")
```
[More...](https://labstack.com/echo/guide/static-files/)
### [Template Rendering](https://labstack.com/echo/guide/templates/)
### Middleware
```go
// Root level middleware
e.Use(middleware.Logger())
e.Use(middleware.Recover())
// Group level middleware
g := e.Group("/admin")
g.Use(middleware.BasicAuth(func(username, password string) bool {
if username == "joe" && password == "secret" {
return true
}
return false
}))
// Route level middleware
track := func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
println("request to /users")
return next(c)
}
}
e.Get("/users", func(c echo.Context) error {
return c.String(http.StatusOK, "/users")
}, track)
```
[More...](https://labstack.com/echo/guide/middleware/)
### Next
- Browse [recipes](https://labstack.com/echo/recipes/hello-world)
- Head over to [guide](https://labstack.com/echo/guide/installation)
- Head over to [guide](https://labstack.com/echo/guide/installation/)
- Browse [recipes](https://labstack.com/echo/recipes/hello-world/)
### Need help?
- [Hop on to chat](https://gitter.im/labstack/echo)
- [Open an issue](https://github.com/labstack/echo/issues/new)
## Want to support us?
## Support Us
- :star: the project
- [Donate](https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=JD5R56K84A8G4&lc=US&item_name=LabStack&item_number=echo&currency_code=USD&bn=PP-DonationsBF:btn_donate_LG.gif:NonHosted)

View File

@@ -79,8 +79,8 @@ type (
// Set saves data in the context.
Set(string, interface{})
// Bind binds the request body into provided type `i`. The default binder does
// it based on Content-Type header.
// Bind binds the request body into provided type `i`. The default binder
// does it based on Content-Type header.
Bind(interface{}) error
// Render renders a template with data and sends a text/html response with status

View File

@@ -42,6 +42,7 @@ package echo
import (
"bytes"
"encoding/json"
"encoding/xml"
"errors"
"fmt"
"io"
@@ -52,8 +53,6 @@ import (
"strings"
"sync"
"encoding/xml"
"github.com/labstack/echo/engine"
"github.com/labstack/gommon/log"
)
@@ -493,6 +492,9 @@ func (e *Echo) ServeHTTP(rq engine.Request, rs engine.Response) {
func (e *Echo) Run(s engine.Server) {
s.SetHandler(e)
s.SetLogger(e.logger)
if e.Debug() {
e.logger.Debug("message=running in debug mode")
}
e.logger.Error(s.Start())
}
@@ -511,7 +513,7 @@ func (e *HTTPError) Error() string {
return e.Message
}
func (binder) Bind(i interface{}, c Context) (err error) {
func (b *binder) Bind(i interface{}, c Context) (err error) {
rq := c.Request()
ct := rq.Header().Get(ContentType)
err = ErrUnsupportedMediaType

View File

@@ -23,8 +23,8 @@ type (
}
responseAdapter struct {
writer http.ResponseWriter
*Response
http.ResponseWriter
response *Response
}
)
@@ -108,15 +108,23 @@ func (r *Response) reset(w http.ResponseWriter, a *responseAdapter, h engine.Hea
r.writer = w
}
func (a *responseAdapter) Header() http.Header {
return a.writer.Header()
func (a *responseAdapter) Write(b []byte) (n int, err error) {
return a.response.Write(b)
}
func (a *responseAdapter) WriteHeader(code int) {
a.writer.WriteHeader(code)
func (a *responseAdapter) Flush() {
a.ResponseWriter.(http.Flusher).Flush()
}
func (a *responseAdapter) Hijack() (net.Conn, *bufio.ReadWriter, error) {
return a.ResponseWriter.(http.Hijacker).Hijack()
}
func (a *responseAdapter) CloseNotify() <-chan bool {
return a.ResponseWriter.(http.CloseNotifier).CloseNotify()
}
func (a *responseAdapter) reset(w http.ResponseWriter, r *Response) {
a.writer = w
a.Response = r
a.ResponseWriter = w
a.response = r
}