Skip to content

Commit

Permalink
updated migration guide
Browse files Browse the repository at this point in the history
Signed-off-by: Vishal Rana <vr@labstack.com>
  • Loading branch information
vishr committed Nov 15, 2016
1 parent 2f70d3e commit c5a3575
Show file tree
Hide file tree
Showing 17 changed files with 147 additions and 237 deletions.
2 changes: 1 addition & 1 deletion README.md
Expand Up @@ -21,7 +21,7 @@

## Performance

![Performance](http://i.imgur.com/F2V7TfO.png)
![Performance](https://i.imgur.com/F2V7TfO.png)

## Quick Start

Expand Down
40 changes: 22 additions & 18 deletions context.go
Expand Up @@ -13,8 +13,6 @@ import (
"os"
"path/filepath"
"strings"

"golang.org/x/net/websocket"
)

type (
Expand Down Expand Up @@ -175,16 +173,15 @@ type (
}

context struct {
request *http.Request
response *Response
webSocket *websocket.Conn
path string
pnames []string
pvalues []string
query url.Values
handler HandlerFunc
store Map
echo *Echo
request *http.Request
response *Response
path string
pnames []string
pvalues []string
query url.Values
handler HandlerFunc
store Map
echo *Echo
}
)

Expand Down Expand Up @@ -238,15 +235,22 @@ func (c *context) SetPath(p string) {
c.path = p
}

func (c *context) Param(name string) (value string) {
l := len(c.pnames)
func (c *context) Param(name string) string {
for i, n := range c.pnames {
if n == name && i < l {
value = c.pvalues[i]
break
if i < len(c.pnames) {
if strings.HasPrefix(n, name) {
return c.pvalues[i]
}

// Param name with aliases
for _, p := range strings.Split(n, ",") {
if p == name {
return c.pvalues[i]
}
}
}
}
return
return ""
}

func (c *context) ParamNames() []string {
Expand Down
12 changes: 12 additions & 0 deletions context_test.go
Expand Up @@ -250,6 +250,18 @@ func TestContextPathParam(t *testing.T) {
assert.Equal(t, "501", c.Param("fid"))
}

func TestContextPathParamNamesAlais(t *testing.T) {
e := New()
req, _ := http.NewRequest(GET, "/", nil)
c := e.NewContext(req, nil)

c.SetParamNames("id,name")
c.SetParamValues("joe")

assert.Equal(t, "joe", c.Param("id"))
assert.Equal(t, "joe", c.Param("name"))
}

func TestContextFormValue(t *testing.T) {
f := make(url.Values)
f.Set("name", "Jon Snow")
Expand Down
9 changes: 8 additions & 1 deletion router.go
@@ -1,5 +1,7 @@
package echo

import "strings"

type (
// Router is the registry of all registered routes for an `Echo` instance for
// request matching and URL path parameter parsing.
Expand Down Expand Up @@ -170,7 +172,12 @@ func (r *Router) insert(method, path string, h HandlerFunc, t kind, ppath string
if h != nil {
cn.addHandler(method, h)
cn.ppath = ppath
cn.pnames = pnames
for i, n := range cn.pnames {
// Param name aliases
if !strings.Contains(n, pnames[i]) {
cn.pnames[i] += "," + pnames[i]
}
}
}
}
return
Expand Down
9 changes: 6 additions & 3 deletions router_test.go
Expand Up @@ -3,6 +3,7 @@ package echo
import (
"fmt"
"net/http"
"strings"
"testing"

"github.com/stretchr/testify/assert"
Expand Down Expand Up @@ -823,9 +824,11 @@ func TestRouterAPI(t *testing.T) {
c := e.NewContext(nil, nil).(*context)
for _, route := range gitHubAPI {
r.Find(route.Method, route.Path, c)
for i, n := range c.pnames {
if assert.NotEmpty(t, n) {
assert.Equal(t, n, c.pnames[i])
for _, n := range c.pnames {
for _, p := range strings.Split(n, ",") {
if assert.NotEmpty(t, p) {
assert.Equal(t, c.Param(p), ":"+p)
}
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion website/Makefile
@@ -1,2 +1,2 @@
build:
rm -rf public && hugo
rm -rf public/v3 && hugo
3 changes: 2 additions & 1 deletion website/config.json
@@ -1,9 +1,10 @@
{
"baseurl": "https://echo.labstack.com",
"baseurl": "https://echo.labstack.com/",
"languageCode": "en-us",
"title": "Echo - Fast and unfancy HTTP server framework for Go (Golang)",
"canonifyurls": true,
"googleAnalytics": "UA-85059636-2",
"publishdir": "public/v3",
"permalinks": {
"guide": "/guide/:filename",
"middleware": "/middleware/:filename",
Expand Down
79 changes: 15 additions & 64 deletions website/content/guide/customization.md
Expand Up @@ -11,88 +11,39 @@ description = "Customizing Echo"

### HTTP Error Handler

`Echo#SetHTTPErrorHandler(h HTTPErrorHandler)` registers a custom `Echo#HTTPErrorHandler`.

Default HTTP error handler rules:

- If error is of type `Echo#HTTPError` it sends HTTP response with status code `HTTPError.Code`
and message `HTTPError.Message`.
- Else it sends `500 - Internal Server Error`.
- If debug mode is enabled, it uses `error.Error()` as status message.

### Debug

`Echo#SetDebug(on bool)` enable/disable debug mode.
You can also set a custom HTTP error handler using `Echo#HTTPErrorHandler`.

### Logging
### Debugging

#### Custom Logger
`Echo#Debug` enables/disables debug mode.

`Echo#SetLogger(l log.Logger)`

SetLogger defines a custom logger.
### Logging

#### Log Output

`Echo#SetLogOutput(w io.Writer)` sets the output destination for the logger. Default
value `os.Stdout`
`Echo#Logger.SetOutput(io.Writer)` sets the output destination for the logger.
Default value `os.Stdout`

To completely disable logs use `Echo#SetLogOutput(io.Discard)`
To completely disable logs use `Echo#Logger.SetOutput(io.Discard)` or `Echo#Logger.SetLevel(log.OFF)`

#### Log Level

`Echo#SetLogLevel(l log.Level)`
`Echo#Logger.SetLevel(log.Lvl)`

SetLogLevel sets the log level for the logger. Default value `5` (OFF).
SetLogLevel sets the log level for the logger. Default value `OFF`.
Possible values:

- `0` (DEBUG)
- `1` (INFO)
- `2` (WARN)
- `3` (ERROR)
- `4` (FATAL)
- `5` (OFF)

### HTTP Engine

Echo currently supports standard and [fasthttp](https://github.com/valyala/fasthttp)
server engines. Echo utilizes interfaces to abstract the internal implementation
of these servers so you can seamlessly switch from one engine to another based on
your preference.

#### Running a standard HTTP server

`e.Run(standard.New(":1323"))`

#### Running a fasthttp server

`e.Run(fasthttp.New(":1323"))`

#### Running a server with TLS configuration

`e.Run(<engine>.WithTLS(":1323", "<certFile>", "<keyFile>"))`

#### Running a server with engine configuration

`e.Run(<engine>.WithConfig(<config>))`

##### Configuration

```go
Config struct {
Address string // TCP address to listen on.
Listener net.Listener // Custom `net.Listener`. If set, server accepts connections on it.
TLSCertFile string // TLS certificate file path.
TLSKeyFile string // TLS key file path.
ReadTimeout time.Duration // Maximum duration before timing out read of the request.
WriteTimeout time.Duration // Maximum duration before timing out write of the response.
}
```

#### Access internal server instance and configure its properties
- `DEBUG`
- `INFO`
- `WARN`
- `ERROR`
- `OFF`

```go
s := standard.New(":1323")
s.MaxHeaderBytes = 1 << 20
e.Run(s)
```
You can also set a custom logger using `Echo#Logger`.
61 changes: 13 additions & 48 deletions website/content/guide/faq.md
Expand Up @@ -9,82 +9,47 @@ description = "Frequently asked questions in Echo"

## FAQ

Q: **How to retrieve `*http.Request` and `http.ResponseWriter` from `echo.Context`?**
Q: How to retrieve `*http.Request` and `http.ResponseWriter` from `echo.Context`?

- `http.Request` > `c.Request().(*standard.Request).Request`
- `http.Request` > `c.Request()`
- `http.ResponseWriter` > `c.Response()`

> Standard engine only
Q: **How to use standard handler `func(http.ResponseWriter, *http.Request)` with Echo?**
Q: How to use standard handler `func(http.ResponseWriter, *http.Request)` with Echo?

```go
func handler(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, "Handler!")
}

func main() {
e := echo.New()
e.GET("/", standard.WrapHandler(http.HandlerFunc(handler)))
e.Run(standard.New(":1323"))
}
```

Q: **How to use fasthttp handler `func(fasthttp.RequestCtx)` with Echo?**

```go
func handler(c *fh.RequestCtx) {
io.WriteString(c, "Handler!")
io.WriteString(w, "Echo!")
}

func main() {
e := echo.New()
e.GET("/", fasthttp.WrapHandler(handler))
e.Run(fasthttp.New(":1323"))
e.GET("/", echo.WrapHandler(http.HandlerFunc(handler)))
e.Start(":1323")
}
```

Q: **How to use standard middleware `func(http.Handler) http.Handler` with Echo?**
Q: How to use standard middleware `func(http.Handler) http.Handler` with Echo?

```go
func middleware(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
println("Middleware!")
println("middleware")
h.ServeHTTP(w, r)
})
}

func main() {
e := echo.New()
e.Use(standard.WrapMiddleware(middleware))
e.Use(echo.WrapMiddleware(middleware))
e.GET("/", func(c echo.Context) error {
return c.String(http.StatusOK, "OK")
return c.String(http.StatusOK, "Echo!")
})
e.Run(standard.New(":1323"))
e.Start(":1323")
}
```

Q: **How to use fasthttp middleware `func(http.Handler) http.Handler` with Echo?**
Q: How to run Echo on a specific IP address?

```go
func middleware(h fh.RequestHandler) fh.RequestHandler {
return func(ctx *fh.RequestCtx) {
println("Middleware!")
h(ctx)
}
}

func main() {
e := echo.New()
e.Use(fasthttp.WrapMiddleware(middleware))
e.GET("/", func(c echo.Context) error {
return c.String(http.StatusOK, "OK")
})
e.Run(fasthttp.New(":1323"))
}
e.Start("<ip>:<port>")
```

<!-- ### Q: How to run Echo on specific IP and port?
```go
``` -->
4 changes: 2 additions & 2 deletions website/content/guide/installation.md
Expand Up @@ -15,9 +15,9 @@ Echo is developed and tested using Go `1.6.x` and `1.7.x`
$ go get -u github.com/labstack/echo
```

> Ideally, you should rely on a [package manager](https://github.com/avelino/awesome-go#package-management) like glide or govendor to use a specific [version](https://github.com/labstack/echo/releases) of Echo.
> Ideally you should rely on a [package manager](https://github.com/avelino/awesome-go#package-management) like glide or govendor to use a specific [version](https://github.com/labstack/echo/releases) of Echo.
### [Migrating from v1](/guide/migrating)
### [Migrating Guide](/guide/migration)

Echo follows [semantic versioning](http://semver.org) managed through GitHub releases.
Specific version of Echo can be installed using a [package manager](https://github.com/avelino/awesome-go#package-management).

0 comments on commit c5a3575

Please sign in to comment.