mirror of
https://github.com/labstack/echo.git
synced 2025-06-19 00:27:34 +02:00
Dropped support for func(http.Handler) http.Handler middleware
Signed-off-by: Vishal Rana <vr@labstack.com>
This commit is contained in:
115
examples/web/server.go
Normal file
115
examples/web/server.go
Normal file
@ -0,0 +1,115 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"io"
|
||||
"net/http"
|
||||
|
||||
"html/template"
|
||||
|
||||
"github.com/labstack/echo"
|
||||
)
|
||||
|
||||
type (
|
||||
// Template provides HTML template rendering
|
||||
Template struct {
|
||||
templates *template.Template
|
||||
}
|
||||
|
||||
user struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
}
|
||||
)
|
||||
|
||||
var (
|
||||
users map[string]user
|
||||
)
|
||||
|
||||
// Render HTML
|
||||
func (t *Template) Render(w io.Writer, name string, data interface{}) error {
|
||||
return t.templates.ExecuteTemplate(w, name, data)
|
||||
}
|
||||
|
||||
func welcome(c *echo.Context) {
|
||||
c.Render(http.StatusOK, "welcome", "Joe")
|
||||
}
|
||||
|
||||
func createUser(c *echo.Context) error {
|
||||
u := new(user)
|
||||
if err := c.Bind(u); err != nil {
|
||||
return err
|
||||
}
|
||||
users[u.ID] = *u
|
||||
return c.JSON(http.StatusCreated, u)
|
||||
}
|
||||
|
||||
func getUsers(c *echo.Context) error {
|
||||
return c.JSON(http.StatusOK, users)
|
||||
}
|
||||
|
||||
func getUser(c *echo.Context) error {
|
||||
return c.JSON(http.StatusOK, users[c.P(0)])
|
||||
}
|
||||
|
||||
func main() {
|
||||
e := echo.New()
|
||||
|
||||
// Middleware
|
||||
e.Use(echo.Logger)
|
||||
|
||||
// Serve index file
|
||||
e.Index("public/index.html")
|
||||
|
||||
// Serve static files
|
||||
e.Static("/scripts", "public/scripts")
|
||||
|
||||
//--------
|
||||
// Routes
|
||||
//--------
|
||||
e.Post("/users", createUser)
|
||||
e.Get("/users", getUsers)
|
||||
e.Get("/users/:id", getUser)
|
||||
|
||||
//-----------
|
||||
// Templates
|
||||
//-----------
|
||||
t := &Template{
|
||||
// Cached templates
|
||||
templates: template.Must(template.ParseFiles("public/views/welcome.html")),
|
||||
}
|
||||
e.Renderer(t)
|
||||
e.Get("/welcome", welcome)
|
||||
|
||||
//-------
|
||||
// Group
|
||||
//-------
|
||||
|
||||
// Group with parent middleware
|
||||
a := e.Group("/admin")
|
||||
a.Use(func(c *echo.Context) {
|
||||
// Security middleware
|
||||
})
|
||||
a.Get("", func(c *echo.Context) {
|
||||
c.String(http.StatusOK, "Welcome admin!")
|
||||
})
|
||||
|
||||
// Group with no parent middleware
|
||||
g := e.Group("/files", func(c *echo.Context) {
|
||||
// Security middleware
|
||||
})
|
||||
g.Get("", func(c *echo.Context) {
|
||||
c.String(http.StatusOK, "Your files!")
|
||||
})
|
||||
|
||||
// Start server
|
||||
e.Run(":4444")
|
||||
}
|
||||
|
||||
func init() {
|
||||
users = map[string]user{
|
||||
"1": user{
|
||||
ID: "1",
|
||||
Name: "Wreck-It Ralph",
|
||||
},
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user