Categorygithub.com/webx-top/echo
modulepackage
1.14.5
Repository: https://github.com/webx-top/echo.git
Documentation: pkg.go.dev

# README

Echo

Go 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.21

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

namevalue
nameJoe Smith
email[email protected]
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

namevalue
nameJoe Smith
email[email protected]
avataravatar
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)

Cookie

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

MiddlewareImport pathDescription
BasicAuthgithub.com/webx-top/echo/middlewareHTTP basic authentication
BodyLimitgithub.com/webx-top/echo/middlewareLimit request body
Gzipgithub.com/webx-top/echo/middlewareSend gzip HTTP response
Securegithub.com/webx-top/echo/middlewareProtection against attacks
CORSgithub.com/webx-top/echo/middlewareCross-Origin Resource Sharing
CSRFgithub.com/webx-top/echo/middlewareCross-Site Request Forgery
Loggithub.com/webx-top/echo/middlewareLog HTTP requests
MethodOverridegithub.com/webx-top/echo/middlewareOverride request method
Recovergithub.com/webx-top/echo/middlewareRecover from panics
HTTPSRedirectgithub.com/webx-top/echo/middlewareRedirect HTTP requests to HTTPS
HTTPSWWWRedirectgithub.com/webx-top/echo/middlewareRedirect HTTP requests to WWW HTTPS
WWWRedirectgithub.com/webx-top/echo/middlewareRedirect non WWW requests to WWW
NonWWWRedirectgithub.com/webx-top/echo/middlewareRedirect WWW requests to non WWW
AddTrailingSlashgithub.com/webx-top/echo/middlewareAdd trailing slash to the request URI
RemoveTrailingSlashgithub.com/webx-top/echo/middlewareRemove trailing slash from the request URI
Staticgithub.com/webx-top/echo/middlewareServe static files
MaxAllowedgithub.com/webx-top/echo/middlewareMaxAllowed limits simultaneous requests; can help with high traffic load
RateLimitgithub.com/webx-top/echo/middleware/ratelimitRate limiting HTTP requests
Languagegithub.com/webx-top/echo/middleware/languageMulti-language support
Sessiongithub.com/webx-top/echo/middleware/sessionSessions Manager
JWTgithub.com/webx-top/echo/middleware/jwtJWT authentication
Markdowngithub.com/webx-top/echo/middleware/markdownMarkdown rendering
Rendergithub.com/webx-top/echo/middleware/renderHTML template rendering
ReverseProxygithub.com/webx-top/reverseproxyReverse proxy

Handler Wrapper list

WrapperImport pathDescription
Websocketgithub.com/webx-top/echo/handler/websocketExample
Sockjsgithub.com/webx-top/echo/handler/sockjsExample
Oauth2github.com/webx-top/echo/handler/oauth2Example
Pprofgithub.com/webx-top/echo/handler/pprof-

Cases

Credits

License

Apache 2

# Packages

No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author

# Functions

No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
ContentTypeByExtension returns the MIME type associated with the file based on its extension.
CookieExpires 设置过期时间 所有浏览器都支持 如果仅仅设置Expires,因为过期时间是固定的,所以不会导致保存Cookie时被续期.
CookieMaxAge 设置有效时长(秒) IE6/7/8不支持 如果同时设置了MaxAge和Expires,则优先使用MaxAge 设置MaxAge则代表每次保存Cookie都会续期,因为MaxAge是基于保存时间来设置的.
CookieSameSite 设置SameSite.
CopyCookieOptions copy cookie options.
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
DefaultSkipper returns false which processes the middleware.
No description provided by the author
No description provided by the author
Dump 输出对象和数组的结构信息.
No description provided by the author
No description provided by the author
ExcludeFieldName 排除字段.
No description provided by the author
No description provided by the author
No description provided by the author
FlatStructToForm 映射struct到form.
No description provided by the author
No description provided by the author
FormatFieldValue 格式化字段值.
FormNames user[name][test].
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
HandlerName returns the handler name.
HandlerPath returns the handler path.
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
IncludeFieldName 包含字段.
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
Methods returns methods.
No description provided by the author
No description provided by the author
NamedStructMap 自动将map值映射到结构体.
No description provided by the author
New creates an instance of Echo.
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
NewContext creates a Context object.
NewCookie 新建cookie对象.
No description provided by the author
NewCookier create a cookie instance.
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
NewKVData 键值对数据.
No description provided by the author
NewKVxData 键值对数据.
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
https://developers.google.cn/search/docs/crawling-indexing/block-indexing?hl=zh-cn#http-response-header.
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
T 标记为多语言文本(fake).
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
WrapHandler wrap `interface{}` into `echo.Handler`.
WrapMiddleware wrap `interface{}` into `echo.Middleware`.
WrapMiddlewareFromHandler wrap `echo.HandlerFunc` into `echo.Middleware`.
WrapMiddlewareFromStdHandleFunc wrap `func(http.ResponseWriter, *http.Request)` into `echo.Middleware`.
WrapMiddlewareFromStdHandleFuncd wrap `func(http.ResponseWriter, *http.Request)` into `echo.Middleware`.
WrapMiddlewareFromStdHandler wrap `http.HandlerFunc` into `echo.Middleware`.

# Constants

No description provided by the author
No description provided by the author
CONNECT HTTP method.
Content Type.
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
DELETE HTTP method.
No description provided by the author
GET HTTP method.
HEAD HTTP method.
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
Access control.
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
Security.
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
OPTIONS HTTP method.
PATCH HTTP method.
POST
POST HTTP method.
PUT HTTP method.
HTTP Scheme.
No description provided by the author
No description provided by the author
4 KB.
TRACE HTTP method.

# Variables

ArrayFieldNameFormatter 格式化函数(struct->form).
No description provided by the author
No description provided by the author
DateToTimestamp 日期时间转时间戳.
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
DefaultFieldNameFormatter 默认格式化函数(struct->form).
No description provided by the author
DefaultHTMLFilter html filter (`form_filter:"html"`).
No description provided by the author
DefaultNopFilter 默认过滤器(map->struct).
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
JoinValues 组合数组为字符串.
LowerCaseFirstLetter 小写首字母(struct->form).
No description provided by the author
No description provided by the author
SplitValues 拆分字符串为数组.
No description provided by the author
No description provided by the author
No description provided by the author
TimestampToDate 时间戳转日期时间.
No description provided by the author

# Structs

No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
CookieOptions cookie options.
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
KV 键值对.
KVData 键值对数据(保持顺序).
KV 键值对.
KVxData 键值对数据(保持顺序).
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
SessionOptions stores configuration for a session or session store.
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author

# Interfaces

No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
Context represents context for the current request.
No description provided by the author
No description provided by the author
No description provided by the author
Cookier interface.
Data 响应数据.
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
Sessioner Wraps thinly gorilla-session methods.
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
Validator is the interface that wraps the Validate method.
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author

# Type aliases

No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author