快速的HTTP router+微型 Web 框架:Echo
Echo 是一個用 Go 語言開發的快速 HTTP 路由器(零內存分配)和微型 Web 框架。
特性:
-
Zippy router.
-
Extensible middleware/handler, supports:
-
func(*echo.Context)
-
http.Handler
-
http.HandlerFunc
-
func(http.ResponseWriter, *http.Request)
-
func(*echo.Context)
-
func(echo.HandlerFunc) echo.HandlerFunc
-
func(http.Handler) http.Handler
-
http.Handler
-
http.HandlerFunc
-
func(http.ResponseWriter, *http.Request)
-
Middleware
-
Handler
-
Handy encoding/decoding functions.
-
支持靜態文件處理
示例代碼:
package main
import (
"net/http"
"github.com/labstack/echo"
mw "github.com/labstack/echo/middleware"
"github.com/rs/cors"
"github.com/thoas/stats"
)
type user struct {
ID string `json:"id"`
Name string `json:"name"`
}
var users map[string]user
func init() {
users = map[string]user{
"1": user{
ID: "1",
Name: "Wreck-It Ralph",
},
}
}
func createUser(c *echo.Context) {
u := new(user)
if c.Bind(u) {
users[u.ID] = *u
c.JSON(http.StatusCreated, u)
}
}
func getUsers(c *echo.Context) {
c.JSON(http.StatusOK, users)
}
func getUser(c *echo.Context) {
c.JSON(http.StatusOK, users[c.P(0)])
}
func main() {
e := echo.New()
//*************************//
// Built-in middleware //
//*************************//
e.Use(mw.Logger)
//****************************//
// Third-party middleware //
//****************************//
// https://github.com/rs/cors
e.Use(cors.Default().Handler)
// https://github.com/thoas/stats
s := stats.New()
e.Use(s.Handler)
// Route
e.Get("/stats", func(c *echo.Context) {
c.JSON(200, s.Data())
})
// Serve index file
e.Index("public/index.html")
// Serve static files
e.Static("/js", "public/js")
//************//
// Routes //
//************//
e.Post("/users", createUser)
e.Get("/users", getUsers)
e.Get("/users/:id", getUser)
// Start server
e.Run(":8080")
} 本文由用戶 dwd4 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!