labstack / echo
- среда, 6 апреля 2016 г. в 03:12:48
Go
Echo is a fast and unfancy web framework for Go (Golang). Up to 10x faster than the rest.
go get gopkg.in/labstack/echo.v1
.$ go get github.com/labstack/echo/...
Create server.go
package main
import (
"net/http"
"github.com/labstack/echo"
"github.com/labstack/echo/engine/standard"
)
func main() {
e := echo.New()
e.Get("/", func(c echo.Context) error {
return c.String(http.StatusOK, "Hello, World!")
})
e.Run(standard.New(":1323"))
}
Start server
$ go run server.go
Browse to http://localhost:1323 and you should see Hello, World! on the page.
e.Post("/users", saveUser)
e.Get("/users/:id", getUser)
e.Put("/users/:id", updateUser)
e.Delete("/users/:id", deleteUser)
func getUser(c echo.Context) error {
// User ID from path `users/:id`
id := c.Param("id")
}
/show?team=x-men&member=wolverine
func show(c echo.Context) error {
// Get team and member from the query string
team := c.QueryParam("team")
member := c.QueryParam("member")
}
application/x-www-form-urlencoded
POST
/save
name | value |
---|---|
name | Joe Smith |
joe@labstack.com |
func save(c echo.Context) error {
// Get name and email
name := c.FormValue("name")
email := c.FormParam("email")
}
multipart/form-data
POST
/save
name | value |
---|---|
name | Joe Smith |
joe@labstack.com | |
avatar | avatar |
func save(c echo.Context) error {
// Get name and email
name := c.FormValue("name")
email := c.FormParam("email")
//------------
// Get avatar
//------------
avatar, err := c.FormFile("avatar")
if err != nil {
return err
}
src, err := file.Open()
if err != nil {
return err
}
defer src.Close()
// Destination
file, err := os.Create(file.Filename)
if err != nil {
return err
}
defer file.Close()
// Copy
if _, err = io.Copy(file, avatar); err != nil {
return err
}
}
JSON
or XML
payload into Go struct based on Content-Type
request header.JSON
or XML
with status code.type User struct {
Name string `json:"name" xml:"name"`
Email string `json:"email" xml:"email"`
}
e.Post("/users", func(c echo.Context) error {
u := new(User)
if err := c.Bind(u); err != nil {
return err
}
return c.JSON(http.StatusCreated, u)
// or
// return c.XML(http.StatusCreated, u)
})
Server any file from static directory for path /static/*
.
e.Static("/static", "static")
// Root level middleware
e.Use(middleware.Logger())
e.Use(middleware.Recover())
// Group level middleware
g := e.Group("/admin")
g.Use(middleware.BasicAuth(func(username, password string) bool {
if username == "joe" && password == "secret" {
return true
}
return false
}))
// Route level middleware
track := func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
println("request to /users")
return next(c)
}
}
e.Get("/users", func(c echo.Context) error {
return c.String(http.StatusOK, "/users")
}, track)
Use issues for everything