Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Middleware documentation/examples #50

Closed
olliephillips opened this issue May 5, 2015 · 2 comments
Closed

Middleware documentation/examples #50

olliephillips opened this issue May 5, 2015 · 2 comments
Assignees
Labels

Comments

@olliephillips
Copy link
Contributor

Any documentation/advice on creating own middleware for Echo? There are things that I see to be different to other frameworks - no need to pass control to the next middleware in the chain for one?

I'm writing a simple basicauth middleware - it partially works but returns and flow passes to the route handler's function, so I get double output:- a 401 then the route's func handler response. How should I approach it to halt in the middleware and serve just the 401 Unauthorized?

Full disclosure: I'm fairly new to Go, so I'm still bit of a hacker and apologies if what I've asked seems basic or approached in the wrong way.

vishr added a commit that referenced this issue May 6, 2015
Signed-off-by: Vishal Rana <vr@labstack.com>
@vishr
Copy link
Member

vishr commented May 6, 2015

The project is pretty new and I haven't got time to write all the documentation, but I am working on it.

You can do something like below, with this all HTTP error handling is centralized http://labstack.github.io/echo/guide/#customization.

package main

import (
    "errors"
    "net/http"

    "github.com/labstack/echo"
)

func main() {
    e := echo.New()
    e.Use(func(c *echo.Context) *echo.HTTPError {
        // Handled by central HTTP error handler
        return &echo.HTTPError{
            Code:  401,
            Error: errors.New("unauthorized"),
        }
        // return nil
    })
    e.Get("/welcome", welcome)
    e.Run(":4444")
}

func welcome(c *echo.Context) *echo.HTTPError {
    return c.String(http.StatusOK, "Welcome!")
}

@olliephillips
Copy link
Contributor Author

Hi, really appreciate you taking the time to reply. Thank you for the steer and commit
I had this:

func TestMiddleware(h http.Handler) http.Handler {

    return http.HandlerFunc(func (w http.ResponseWriter, r *http.Request) {

        username, password, ok := r.BasicAuth()

        // No Authentication header
        if ok != true {
            http.Error(w, http.StatusText(401), 401)
            return
        }

        // Check validate credentials
        ok = validateUser(username, password) // Off to database
        fmt.Println(ok)
        if ok != true {
            http.Error(w, http.StatusText(401), 401)
            return
        }

        // Authenticated user
        h.ServeHTTP(w, r)
        return
    })
}

which I've been able to refactor to this using the new echo.HTTPError return , which feels much cleaner

func TestMiddleware(c *echo.Context) *echo.HTTPError {

    username, password, ok := c.Request.BasicAuth()

    // No Authentication header
    if ok != true {
        return &echo.HTTPError{
            Code:  401,
                Error: errors.New("Unauthorized"),
            }
    }   

    // Check validate credentials
    ok = validateUser(username, password) // Off to database

    if ok != true {
        return &echo.HTTPError{
            Code:  401,
                Error: errors.New("Unauthorized"),
            }
    }

    // Authenticated user       
        return nil

}

Thanks again. Hope your Echo project is a big success!

@vishr vishr added the question label May 10, 2015
@vishr vishr self-assigned this May 10, 2015
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants