-
-
Notifications
You must be signed in to change notification settings - Fork 239
/
Copy pathecho.go
50 lines (39 loc) · 1.09 KB
/
echo.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package examples
import (
"net/http"
"github.com/dgrijalva/jwt-go"
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
)
// EchoHandler creates http.Handler using echo framework.
//
// Routes:
//
// GET /login authenticate user and return JWT token
// GET /restricted/hello return "hello, world!" (requires authentication)
func EchoHandler() http.Handler {
e := echo.New()
e.POST("/login", func(ctx echo.Context) error {
username := ctx.FormValue("username")
password := ctx.FormValue("password")
if username == "ford" && password == "betelgeuse7" {
// create token
token := jwt.New(jwt.SigningMethodHS256)
// generate encoded token and send it as response
t, err := token.SignedString([]byte("secret"))
if err != nil {
return err
}
return ctx.JSON(http.StatusOK, map[string]string{
"token": t,
})
}
return echo.ErrUnauthorized
})
r := e.Group("/restricted")
r.Use(middleware.JWT([]byte("secret"))) //nolint
r.GET("/hello", func(ctx echo.Context) error {
return ctx.String(http.StatusOK, "hello, world!")
})
return e
}