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

Updated website

Signed-off-by: Vishal Rana <vr@labstack.com>
This commit is contained in:
Vishal Rana
2016-03-10 21:40:25 -08:00
parent 25e72d623e
commit 91e5f755ad
12 changed files with 145 additions and 158 deletions

View File

@ -1,5 +1,12 @@
# **WORK IN PROGRESS!** # *NOTICE*
- Master branch, website and godoc now points to Echo v2.
- It is advisable to migrate to v2. (https://labstack.com/echo/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
- Docs: https://github.com/labstack/echo/tree/v1.3/website/content
# [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) # [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)
@ -12,13 +19,13 @@ import (
"github.com/labstack/echo" "github.com/labstack/echo"
// "github.com/labstack/echo/engine/fasthttp" // "github.com/labstack/echo/engine/fasthttp"
"github.com/labstack/echo/engine/standard" "github.com/labstack/echo/engine/standard"
mw "github.com/labstack/echo/middleware" "github.com/labstack/echo/middleware"
) )
func main() { func main() {
e := echo.New() e := echo.New()
e.Use(mw.Logger()) e.Use(middleware.Logger())
e.Use(mw.Recover()) e.Use(middleware.Recover())
e.Get("/", echo.HandlerFunc(func(c echo.Context) error { e.Get("/", echo.HandlerFunc(func(c echo.Context) error {
return c.String(200, "Hello, World!") return c.String(200, "Hello, World!")
})) }))

View File

@ -27,55 +27,80 @@ Enable/disable debug mode.
### Log prefix ### Log prefix
`echo#SetLogPrefix(prefix string)` `Echo#SetLogPrefix(prefix string)`
SetLogPrefix sets the prefix for the logger. Default value is `echo`. SetLogPrefix sets the prefix for the logger. Default value is `echo`.
### Log output ### Log output
`echo#SetLogOutput(w io.Writer)` `Echo#SetLogOutput(w io.Writer)`
SetLogOutput sets the output destination for the logger. Default value is `os.Stdout` SetLogOutput sets the output destination for the logger. Default value is `os.Stdout`
To completely disable logs use `Echo#SetLogOutput(io.Discard)`
### Log level ### Log level
`echo#SetLogLevel(l log.Level)` `Echo#SetLogLevel(l log.Level)`
SetLogLevel sets the log level for the logger. Default value is `log.ERROR`. SetLogLevel sets the log level for the logger. Default value is `log.ERROR`.
### Auto index ### Engine
`Echo#AutoIndex(on bool)` #### Standard HTTP server
Enable/disable automatically creating an index page for the directory.
*Example*
```go ```go
e := echo.New() e.Run(standard.New(":1323"))
e.AutoIndex(true)
e.ServerDir("/", "/Users/vr/Projects/echo")
e.Run(":1323")
``` ```
Browse to `http://localhost:1323/` to see the directory listing. ##### From TLS
### Hook
`Echo#Hook(h http.HandlerFunc)`
Hook registers a callback which is invoked from `Echo#ServerHTTP` as the first
statement. Hook is useful if you want to modify response/response objects even
before it hits the router or any middleware.
For example, the following hook strips the trailing slash from the request path.
```go ```go
e.Hook(func(w http.ResponseWriter, r *http.Request) { e.Run(standard.NewFromTLS(":1323", "<certfile>", "<keyfile>"))
path := r.URL.Path
l := len(path) - 1
if path != "/" && path[l] == '/' {
r.URL.Path = path[:l]
}
})
``` ```
##### From config
```go
e.Run(standard.NewFromConfig(&Config{}))
```
#### FastHTTP server
```go
e.Run(fasthttp.New(":1323"))
```
##### From TLS
```go
e.Run(fasthttp.NewFromTLS(":1323", "<certfile>", "<keyfile>"))
```
##### From config
```go
e.Run(fasthttp.NewFromConfig(&Config{}))
```
#### Configuration
##### `Address`
Address to bind.
##### `TLSCertfile`
TLS certificate file path
##### `TLSKeyfile`
TLS key file path
##### `ReadTimeout`
HTTP read timeout
##### `WriteTimeout`
HTTP write timeout

View File

@ -34,8 +34,8 @@ BasicAuth middleware provides an HTTP basic authentication.
```go ```go
g := e.Group("/admin") g := e.Group("/admin")
g.Use(mw.BasicAuth(func(usr, pwd string) bool { e.Use(middleware.BasicAuth(func(username, password string) bool {
if usr == "joe" && pwd == "secret" { if username == "joe" && password == "secret" {
return true return true
} }
return false return false
@ -61,7 +61,7 @@ control to the centralized
*Example* *Example*
```go ```go
e.Use(mw.Recover()) e.Use(middleware.Recover())
``` ```
### [Recipes](https://github.com/labstack/echo/tree/master/recipes/middleware) ### [Recipes](https://github.com/labstack/echox/tree/master/recipe/middleware)

View File

@ -10,9 +10,11 @@ menu:
#### Change log #### Change log
- Echo now uses `Engine` interface to abstract `HTTP` server implementation, allowing - Good news, 85% of the API remains the same.
us to use HTTP servers beyond the standard library. It currently supports standard HTTP server and [FastHTTP](https://github.com/valyala/fasthttp). - `Engine` interface to abstract `HTTP` server implementation, allowing
us to use HTTP servers beyond Go standard library. It currently supports standard HTTP server and [FastHTTP](https://github.com/valyala/fasthttp).
- Context, Request and Response are converted to interfaces. [More...](https://github.com/labstack/echo/issues/146) - Context, Request and Response are converted to interfaces. [More...](https://github.com/labstack/echo/issues/146)
- Handler signature is changed to `func (c echo.Context) error`.
- Moved API's for serving static files into middleware. - Moved API's for serving static files into middleware.
- `Echo#Index` - `Echo#Index`
- `Echo#Favicon` - `Echo#Favicon`
@ -22,10 +24,12 @@ us to use HTTP servers beyond the standard library. It currently supports standa
- Dropped auto wrapping of handler and middleware to enforce compile time check. - Dropped auto wrapping of handler and middleware to enforce compile time check.
- Handler only accepts `Echo#Handler` interface. - Handler only accepts `Echo#Handler` interface.
- Middleware only accepts `Echo#Middleware` interface. - Middleware only accepts `Echo#Middleware` interface.
- `Echo#HandlerFunc` adapter to use of ordinary functions as handlers. - `Echo#HandlerFunc` adapter to use ordinary functions as handlers.
- `Echo#MiddlewareFunc` adapter to use of ordinary functions as middleware. - `Echo#MiddlewareFunc` adapter to use ordinary functions as middleware.
- Middleware is run before hitting the router, which doesn't require `Echo#Hook` API as - Middleware is run before hitting the router, which doesn't require `Echo#Hook` API as
it can be achieved via middleware. it can be achieved via middleware.
- Ability to define middleware at route level. - Ability to define middleware at route level.
#### How? #### How?
Quite easy, browse through [recipes](/recipes/hello-world) freshly converted to v2.

View File

@ -8,9 +8,8 @@ menu:
### Template ### Template
```go `Context#Render(code int, name string, data interface{}) error`
Context.Render(code int, name string, data interface{}) error
```
Renders a template with data and sends a text/html response with status code. Templates Renders a template with data and sends a text/html response with status code. Templates
can be registered using `Echo.SetRenderer()`, allowing us to use any template engine. can be registered using `Echo.SetRenderer()`, allowing us to use any template engine.
@ -23,7 +22,7 @@ type Template struct {
templates *template.Template templates *template.Template
} }
func (t *Template) Render(w io.Writer, name string, data interface{}) error { func (t *Template) Render(w io.Writer, name string, data interface{}, c echo.Context) error {
return t.templates.ExecuteTemplate(w, name, data) return t.templates.ExecuteTemplate(w, name, data)
} }
``` ```
@ -60,87 +59,43 @@ func Hello(c echo.Context) error {
### JSON ### JSON
```go `Context.JSON(code int, v interface{}) error`
Context.JSON(code int, v interface{}) error
```
Sends a JSON HTTP response with status code. Sends a JSON HTTP response with status code.
### JSONP ### JSONP
```go `Context.JSONP(code int, callback string, i interface{}) error`
Context.JSONP(code int, callback string, i interface{}) error
```
Sends a JSONP HTTP response with status code. It uses `callback` to construct the Sends a JSONP HTTP response with status code. It uses `callback` to construct the
JSONP payload. JSONP payload.
### XML ### XML
```go `Context.XML(code int, v interface{}) error`
Context.XML(code int, v interface{}) error
```
Sends an XML HTTP response with status code. Sends an XML HTTP response with status code.
### HTML ### HTML
```go `c.HTML(code int, html string) error`
Context.HTML(code int, html string) error
```
Sends an HTML response with status code. Sends an HTML response with status code.
### String ### String
```go `Context#String(code int, s string) error`
Context.String(code int, s string) error
```
Sends a string response with status code. Sends a string response with status code.
### File ### Attachment
```go `Context#Attachment(file string) (err error)`
Context.File(path, name string, attachment bool) error
```
File sends a response with the content of the file. If `attachment` is set Sends file as an attachment.
to `true`, the client is prompted to save the file with provided `name`,
name can be empty, in that case name of the file is used.
### Static files ### Static files
`Echo.Static(path, root string)` serves static files. For example, code below serves `Echo#Use(middleware.Static("public"))`
files from directory `public/scripts` for any request path starting with `/scripts/`.
```go Serves static files from public folder.
e.Static("/scripts/", "public/scripts")
```
### Serving a file
`Echo.ServeFile(path, file string)` serves a file. For example, code below serves
file `welcome.html` for request path `/welcome`.
```go
e.ServeFile("/welcome", "welcome.html")
```
### Serving an index file
`Echo.Index(file string)` serves root index page - `GET /`. For example, code below
serves root index page from file `public/index.html`.
```go
e.Index("public/index.html")
```
### Serving favicon
`Echo.Favicon(file string)` serves default favicon - `GET /favicon.ico`. For example,
code below serves favicon from file `public/favicon.ico`.
```go
e.Favicon("public/favicon.ico")
```

View File

@ -22,12 +22,10 @@ e.Get("/hello", func(c echo.Context) error {
``` ```
You can use `Echo.Any(path string, h Handler)` to register a handler for all HTTP methods. You can use `Echo.Any(path string, h Handler)` to register a handler for all HTTP methods.
To register it for some methods, use `Echo.Match(methods []string, path string, h Handler)`. If you want to register it for some methods use `Echo.Match(methods []string, path string, h Handler)`.
Echo defines handler function as `func(echo.Context) error` where `echo.Context` primarily
Echo's default handler is `func(*echo.Context) error` where `echo.Context` primarily holds HTTP request and response interfaces.
holds HTTP request and response objects. Echo also has a support for other types
of handlers.
### Match-any ### Match-any
@ -71,20 +69,20 @@ Above routes would resolve in the following order:
### Group ### Group
`Echo.Group(prefix string, m ...Middleware) *Group` `Echo#Group(prefix string, m ...Middleware) *Group`
Routes with common prefix can be grouped to define a new sub-router with optional Routes with common prefix can be grouped to define a new sub-router with optional
middleware. If middleware is passed to the function, it overrides parent middleware middleware. In addition to specified middleware group also inherits parent middleware.
- helpful if you want a completely new middleware stack for the group. To add middleware To add middleware later in the group you can use `Group.Use(m ...Middleware)`.
later you can use `Group.Use(m ...Middleware)`. Groups can also be nested. Groups can also be nested.
In the code below, we create an admin group which requires basic HTTP authentication In the code below, we create an admin group which requires basic HTTP authentication
for routes `/admin/*`. for routes `/admin/*`.
```go ```go
e.Group("/admin") e.Group("/admin")
e.Use(mw.BasicAuth(func(usr, pwd string) bool { e.Use(middleware.BasicAuth(func(username, password string) bool {
if usr == "joe" && pwd == "secret" { if username == "joe" && password == "secret" {
return true return true
} }
return false return false

View File

@ -11,41 +11,12 @@ A fast and unfancy micro web framework for Go.
## Features ## Features
- Fast HTTP router which smartly prioritize routes. - Fast HTTP router which smartly prioritize routes.
- Extensible middleware, supports: - Run with standard HTTP server or FastHTTP server.
- `echo.MiddlewareFunc` - Extensible middleware framework.
- `func(echo.HandlerFunc) echo.HandlerFunc` - Router groups with nesting.
- `echo.HandlerFunc` - Handy functions to send variety of HTTP responses.
- `func(*echo.Context) error`
- `func(http.Handler) http.Handler`
- `http.Handler`
- `http.HandlerFunc`
- `func(http.ResponseWriter, *http.Request)`
- Extensible handler, supports:
- `echo.HandlerFunc`
- `func(*echo.Context) error`
- `http.Handler`
- `http.HandlerFunc`
- `func(http.ResponseWriter, *http.Request)`
- Sub-router/Groups
- Handy functions to send variety of HTTP response:
- HTML
- HTML via templates
- String
- JSON
- JSONP
- XML
- File
- NoContent
- Redirect
- Error
- Build-in support for:
- Favicon
- Index file
- Static files
- WebSocket
- Centralized HTTP error handling. - Centralized HTTP error handling.
- Customizable HTTP request binding function. - Template rendering with any template engine.
- Customizable HTTP response rendering function, allowing you to use any HTML template engine.
## Performance ## Performance
@ -61,7 +32,7 @@ $ go get github.com/labstack/echo
### Hello, World! ### Hello, World!
Create `server.go` Create `main.go`
```go ```go
package main package main
@ -70,42 +41,45 @@ import (
"net/http" "net/http"
"github.com/labstack/echo" "github.com/labstack/echo"
mw "github.com/labstack/echo/middleware" "github.com/labstack/echo/engine/standard"
"github.com/labstack/echo/middleware"
) )
// Handler // Handler
func hello(c echo.Context) error { func hello() echo.HandlerFunc {
return func(c echo.Context) error {
return c.String(http.StatusOK, "Hello, World!\n") return c.String(http.StatusOK, "Hello, World!\n")
} }
}
func main() { func main() {
// Echo instance // Echo instance
e := echo.New() e := echo.New()
// Middleware // Middleware
e.Use(mw.Logger()) e.Use(middleware.Logger())
e.Use(mw.Recover()) e.Use(middleware.Recover())
// Routes // Routes
e.Get("/", hello) e.Get("/", hello())
// Start server // Start server
e.Run(":1323") e.Run(standard.New(":1323"))
} }
``` ```
Start server Start server
```sh ```sh
$ go run server.go $ go run main.go
``` ```
Browse to [http://localhost:1323](http://localhost:1323) and you should see Browse to [http://localhost:1323](http://localhost:1323) and you should see
Hello, World! on the page. Hello, World! on the page.
### Next? ### Next?
- Browse [recipes](https://github.com/labstack/echo/tree/master/recipes) - Browse [recipes](/recipes/hello-world)
- Head over to [guide]({{< relref "guide/installation.md" >}}) - Head over to [guide](/guide/installation")
## Contribute ## Contribute

View File

@ -0,0 +1,19 @@
---
title: CORS
menu:
side:
parent: recipes
weight: 3
---
### Server
`main.go`
{{< embed "cors/main.go" >}}
### Maintainers
- [vishr](https://github.com/vishr)
### [Source Code]({{< source "cors" >}})

View File

@ -1,5 +1,6 @@
--- ---
title: Google App Engine title: Google App Engine
draft: true
menu: menu:
side: side:
parent: recipes parent: recipes

View File

@ -1,5 +1,6 @@
--- ---
title: Website title: Website
draft: true
menu: menu:
side: side:
parent: recipes parent: recipes

View File

@ -1,6 +1,6 @@
<header class="mdl-layout__header"> <header class="mdl-layout__header">
<div class="mdl-layout__header-row"> <div class="mdl-layout__header-row">
<a href="https://labstack.com" class="mdl-navigation__link mdl-layout-title"> <a href="{{ .Site.BaseURL }}" class="mdl-navigation__link mdl-layout-title">
<img src="/images/logo.svg" alt="LabStack"> <img src="/images/logo.svg" alt="LabStack">
</a> </a>
<div class="mdl-layout-spacer"></div> <div class="mdl-layout-spacer"></div>

View File

@ -1,3 +1,6 @@
body, p, ol, ul {
font-size: 16px;
}
footer { footer {
background-color: inherit !important; background-color: inherit !important;
border-top: 2px solid #e0e0e0; border-top: 2px solid #e0e0e0;