1
0
mirror of https://github.com/webx-top/echo synced 2021-12-20 05:52:35 +00:00
Go to file
2021-12-11 16:07:35 +08:00
code improved-code 2021-05-01 16:28:48 +08:00
defaults update 2021-12-08 17:23:09 +08:00
encoding improved 2021-03-07 21:52:51 +08:00
engine update 2021-12-11 16:07:35 +08:00
formfilter improved 2021-09-05 16:01:14 +08:00
handler update 2021-11-22 16:16:08 +08:00
logger update 2018-11-04 17:51:29 +08:00
middleware update 2021-12-11 16:07:35 +08:00
param update 2021-11-02 20:12:10 +08:00
subdomains update 2021-06-18 16:39:17 +08:00
testing fix-test 2021-02-27 13:32:50 +08:00
.editorconfig adding editorconfig for happiness 2015-06-23 22:43:07 -07:00
.gitattributes 升级到v2 2016-02-20 14:13:30 +08:00
.gitignore update 2021-12-11 16:07:35 +08:00
.travis.yml update 2020-07-17 21:50:08 +08:00
binder_test.go improved:binder 2021-09-20 18:22:49 +08:00
binder.go improved:binder 2021-09-20 18:30:47 +08:00
constant.go improved 2021-12-02 12:40:03 +08:00
context_accept_test.go improved:accept 2021-05-15 23:10:15 +08:00
context_accept.go improved:accept 2021-05-15 23:10:15 +08:00
context_store.go update 2019-09-13 12:53:25 +08:00
context_x_base.go fix 2021-12-02 11:06:14 +08:00
context_x_request.go update 2021-11-21 15:35:19 +08:00
context_x_response.go update 2021-12-11 16:07:35 +08:00
context_x_session.go improved-cookie 2020-12-22 19:18:00 +08:00
context_x_store.go fix 2021-11-02 20:56:05 +08:00
context_x_transaction.go update 2020-02-09 18:49:49 +08:00
context.go update 2021-12-11 16:07:35 +08:00
cookie_11.go improved-cookie 2020-12-22 19:18:00 +08:00
cookie_lt11.go improved-cookie 2020-12-22 19:18:00 +08:00
cookie.go update 2021-11-03 00:58:51 +08:00
data_kv_option.go update 2021-06-18 10:39:25 +08:00
data_kv.go update 2021-06-18 10:39:25 +08:00
data.go update 2021-07-14 20:14:54 +08:00
echo_host.go update 2021-09-11 00:54:58 +08:00
echo_test.go update 2021-09-10 21:42:55 +08:00
echo.go update 2021-10-27 12:05:40 +08:00
error.go update 2021-07-31 13:18:29 +08:00
event.go update 2020-08-03 10:39:21 +08:00
group.go update 2021-07-19 20:04:23 +08:00
hashmap_test.go update 2020-08-09 21:40:40 +08:00
hashmap.go update 2020-06-27 10:03:22 +08:00
helper_test.go improved 2020-08-13 15:37:13 +08:00
helper.go update 2021-11-01 15:30:25 +08:00
host_test.go update 2021-09-11 00:14:44 +08:00
host.go update 2021-10-23 20:46:44 +08:00
LICENSE update LICENSE & added middleware 2016-11-27 13:23:31 +08:00
meta_test.go update 2021-07-19 20:04:23 +08:00
meta.go improved 2021-08-03 12:37:51 +08:00
middleware.go update 2018-04-07 17:59:42 +08:00
README.md update 2021-10-24 12:09:03 +08:00
register.go update 2021-11-21 20:16:57 +08:00
router_test.go fix 2021-11-28 22:52:01 +08:00
router.go update 2021-12-01 23:09:58 +08:00
sessioner.go update 2021-05-19 12:43:29 +08:00
transaction_test.go improved transaction 2019-10-01 12:15:17 +08:00
transaction.go improved 2020-02-09 18:56:57 +08:00
translator.go fix:comment 2021-06-06 12:33:18 +08:00
validator.go update 2021-08-16 13:39:14 +08:00
variable_default.go update 2021-03-18 16:36:29 +08:00
variable.go update 2021-12-11 16:07:35 +08:00
wrapper.go update 2021-11-22 12:02:23 +08:00

Echo

Build Status Go Report Card

Echo is a fast and unfancy web framework for Go (Golang). Up to 10x faster than the rest.

This package need >= go 1.13

Features

  • Optimized HTTP router which smartly prioritize routes.
  • Build robust and scalable RESTful APIs.
  • Run with standard HTTP server or FastHTTP server.
  • Group APIs.
  • Extensible middleware framework.
  • Define middleware at root, group or route level.
  • Handy functions to send variety of HTTP responses.
  • Centralized HTTP error handling.
  • Template rendering with any template engine.
  • Define your format for the logger.
  • Highly customizable.

Quick Start

Installation

$ go get github.com/webx-top/echo

Hello, World!

Create server.go

package main

import (
	"net/http"
	"github.com/webx-top/echo"
	"github.com/webx-top/echo/engine/standard"
)

func main() {
	e := echo.New()
	e.Get("/", func(c echo.Context) error {
		return c.String("Hello, World!", http.StatusOK)
	})
	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.

Routing

e.Post("/users", saveUser)
e.Get("/users/:id", getUser)
e.Put("/users/:id", updateUser)
e.Delete("/users/:id", deleteUser)
e.Get("/user/<id:[\\d]+>", getUser)

Path Parameters

func getUser(c echo.Context) error {
	// User ID from path `users/:id`
	id := c.Param("id")
	// or id := c.Paramx("id").Uint64()
}

Query Parameters

/show?team=x-men&member=wolverine

func show(c echo.Context) error {
	// Get team and member from the query string
	team := c.Query("team")
	member := c.Query("member")
	age := c.Queryx("age").Uint()
}

Form application/x-www-form-urlencoded

POST /save

name value
name Joe Smith
email joe@labstack.com
func save(c echo.Context) error {
	// Get name and email
	name := c.Form("name")
	email := c.Form("email")
	age := c.Formx("age").Uint()
}

Form multipart/form-data

POST /save

name value
name Joe Smith
email joe@labstack.com
avatar avatar
func save(c echo.Context) error {
	// Get name and email
	name := c.Form("name")
	email := c.Form("email")

	//------------
	// Get avatar
	//------------
	_, err := c.SaveUploadedFile("avatar","./")
	return err
}

Handling Request

  • Bind JSON or XML payload into Go struct based on Content-Type request header.
  • Render response as 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.MustBind(u); err != nil {
		return err
	}
	return c.JSON(u, http.StatusCreated)
	// or
	// return c.XML(u, http.StatusCreated)
})

Static Content

Server any file from static directory for path /static/*.

e.Use(mw.Static(&mw.StaticOptions{
	Root:"static", //存放静态文件的物理路径
	Path:"/static/", //网址访问静态文件的路径
	Browse:true, //是否在首页显示文件列表
}))

Middleware

// Root level middleware
e.Use(middleware.Log())
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.Handle(c)
	}
}
e.Get("/users", func(c echo.Context) error {
	return c.String("/users", http.StatusOK)
}, track)
e.Get("/setcookie", func(c echo.Context) error {
	c.SetCookie("uid","1")
	return c.String("/setcookie: uid="+c.GetCookie("uid"), http.StatusOK)
})

Session

...
import (
	...
	"github.com/webx-top/echo/middleware/session"
	//boltStore "github.com/webx-top/echo/middleware/session/engine/bolt"
	cookieStore "github.com/webx-top/echo/middleware/session/engine/cookie"
)
...
sessionOptions := &echo.SessionOptions{
	Engine: `cookie`,
	Name:   `SESSIONID`,
	CookieOptions: &echo.CookieOptions{
		Path:     `/`,
		Domain:   ``,
		MaxAge:   0,
		Secure:   false,
		HttpOnly: true,
	},
}

cookieStore.RegWithOptions(&cookieStore.CookieOptions{
	KeyPairs: [][]byte{
		[]byte(`123456789012345678901234567890ab`),
	},
})

e.Use(session.Middleware(sessionOptions))

e.Get("/session", func(c echo.Context) error {
	c.Session().Set("uid",1).Save()
	return c.String(fmt.Sprintf("/session: uid=%v",c.Session().Get("uid")))
})

Websocket

...
import (
	...
	"github.com/admpub/websocket"
	"github.com/webx-top/echo"
	ws "github.com/webx-top/echo/handler/websocket"
)
...

e.AddHandlerWrapper(ws.HanderWrapper)

e.Get("/websocket", func(c *websocket.Conn, ctx echo.Context) error {
	//push(writer)
	go func() {
		var counter int
		for {
			if counter >= 10 { //测试只推10条
				return
			}
			time.Sleep(5 * time.Second)
			message := time.Now().String()
			ctx.Logger().Info(`Push message: `, message)
			if err := c.WriteMessage(websocket.TextMessage, []byte(message)); err != nil {
				ctx.Logger().Error(`Push error: `, err.Error())
				return
			}
			counter++
		}
	}()

	//echo
	ws.DefaultExecuter(c, ctx)
	return nil
})

More...

Sockjs

...
import (
	...
	"github.com/webx-top/echo"
	"github.com/admpub/sockjs-go/v3/sockjs"
	ws "github.com/webx-top/echo/handler/sockjs"
)
...

options := ws.Options{
	Handle: func(c sockjs.Session) error {
		//push(writer)
		go func() {
			var counter int
			for {
				if counter >= 10 { //测试只推10条
					return
				}
				time.Sleep(5 * time.Second)
				message := time.Now().String()
				log.Info(`Push message: `, message)
				if err := c.Send(message); err != nil {
					log.Error(`Push error: `, err.Error())
					return
				}
				counter++
			}
		}()

		//echo
		ws.DefaultExecuter(c)
		return nil
	},
	Options: &sockjs.DefaultOptions,
	Prefix:  "/websocket",
}
options.Wrapper(e)

More...

Other Example

package main

import (
	"net/http"

	"github.com/webx-top/echo"
	// "github.com/webx-top/echo/engine/fasthttp"
	"github.com/webx-top/echo/engine/standard"
	mw "github.com/webx-top/echo/middleware"
)

func main() {
	e := echo.New()
	e.Use(mw.Log())

	e.Get("/", func(c echo.Context) error {
		return c.String("Hello, World!")
	})
	e.Get("/echo/:name", func(c echo.Context) error {
		return c.String("Echo " + c.Param("name"))
	})
	
	e.Get("/std", func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte(`standard net/http handleFunc`))
		w.WriteHeader(200)
	})

	// FastHTTP
	// e.Run(fasthttp.New(":4444"))

	// Standard
	e.Run(standard.New(":4444"))
}

See other examples...

Middleware list

Middleware Import path Description
BasicAuth github.com/webx-top/echo/middleware HTTP basic authentication
BodyLimit github.com/webx-top/echo/middleware Limit request body
Gzip github.com/webx-top/echo/middleware Send gzip HTTP response
Secure github.com/webx-top/echo/middleware Protection against attacks
CORS github.com/webx-top/echo/middleware Cross-Origin Resource Sharing
CSRF github.com/webx-top/echo/middleware Cross-Site Request Forgery
Log github.com/webx-top/echo/middleware Log HTTP requests
MethodOverride github.com/webx-top/echo/middleware Override request method
Recover github.com/webx-top/echo/middleware Recover from panics
HTTPSRedirect github.com/webx-top/echo/middleware Redirect HTTP requests to HTTPS
HTTPSWWWRedirect github.com/webx-top/echo/middleware Redirect HTTP requests to WWW HTTPS
WWWRedirect github.com/webx-top/echo/middleware Redirect non WWW requests to WWW
NonWWWRedirect github.com/webx-top/echo/middleware Redirect WWW requests to non WWW
AddTrailingSlash github.com/webx-top/echo/middleware Add trailing slash to the request URI
RemoveTrailingSlash github.com/webx-top/echo/middleware Remove trailing slash from the request URI
Static github.com/webx-top/echo/middleware Serve static files
MaxAllowed github.com/webx-top/echo/middleware MaxAllowed limits simultaneous requests; can help with high traffic load
RateLimit github.com/webx-top/echo/middleware/ratelimit Rate limiting HTTP requests
Language github.com/webx-top/echo/middleware/language Multi-language support
Session github.com/webx-top/echo/middleware/session Sessions Manager
JWT github.com/webx-top/echo/middleware/jwt JWT authentication
Markdown github.com/webx-top/echo/middleware/markdown Markdown rendering
Render github.com/webx-top/echo/middleware/render HTML template rendering
ReverseProxy github.com/webx-top/reverseproxy Reverse proxy

Handler Wrapper list

Wrapper Import path Description
Websocket github.com/webx-top/echo/handler/websocket Example
Sockjs github.com/webx-top/echo/handler/sockjs Example
Oauth2 github.com/webx-top/echo/handler/oauth2 Example
Pprof github.com/webx-top/echo/handler/pprof -
MVC github.com/webx-top/echo/handler/mvc Example

Cases

Credits

License

Apache 2