elton

package module
v1.13.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 28, 2024 License: MIT Imports: 25 Imported by: 69

README

Elton

license Build Status

Alt

Elton的实现参考了koa以及echo,中间件的调用为洋葱模型:请求由外至内,响应由内至外。主要特性如下:

  • 处理函数(中间件)均以返回error的形式响应出错,方便使用统一的出错处理中间件将出错统一转换为对应的输出(JSON),并根据出错的类型等生成各类统计分析
  • 成功响应数据直接赋值至Context.Body(interface{}),由统一的响应中间件将其转换为对应的输出(JSON,XML)
  • 支持不同种类的事件,如OnBeforeOnDoneOnError等,方便添加各类统计行为

如何使用elton开发WEB后端程序,可以参考一步一步学习如何使用elton

Hello, World!

下面我们来演示如何使用elton返回Hello, World!,并且添加了一些常用的中间件。

package main

import (
	"github.com/vicanso/elton"
	"github.com/vicanso/elton/middleware"
)

func main() {
	e := elton.New()

	// panic处理
	e.Use(middleware.NewRecover())

	// 出错处理
	e.Use(middleware.NewDefaultError())

	// 默认的请求数据解析
	e.Use(middleware.NewDefaultBodyParser())

	// not modified 304的处理
	e.Use(middleware.NewDefaultFresh())
	e.Use(middleware.NewDefaultETag())

	// 响应数据转换为json
	e.Use(middleware.NewDefaultResponder())

	e.GET("/", func(c *elton.Context) error {
		c.Body = &struct {
			Message string `json:"message,omitempty"`
		}{
			"Hello, World!",
		}
		return nil
	})

	e.GET("/books/{id}", func(c *elton.Context) error {
		c.Body = &struct {
			ID string `json:"id,omitempty"`
		}{
			c.Param("id"),
		}
		return nil
	})

	e.POST("/login", func(c *elton.Context) error {
		c.SetContentTypeByExt(".json")
		c.Body = c.RequestBody
		return nil
	})

	err := e.ListenAndServe(":3000")
	if err != nil {
		panic(err)
	}
}
go run main.go

之后在浏览器中打开http://localhost:3000/则能看到返回的Hello, World!

路由

elton每个路由可以添加多个中间件处理函数,根据路由与及HTTP请求方法指定不同的路由处理函数。而全局的中间件则可通过Use方法来添加。

e.Use(...func(*elton.Context) error)
e.Method(path string, ...func(*elton.Context) error)
  • eelton实例化对象
  • Method 为HTTP的请求方法,如:GET, PUT, POST等等
  • path 为HTTP路由路径
  • func(*elton.Context) error 为路由处理函数(中间件),当匹配的路由被请求时,对应的处理函数则会被调用
路由示例

elton的路由使用chi的路由简化而来,下面是两个简单的示例。

// 带参数路由
e.GET("/users/{type}", func(c *elton.Context) error {
	c.BodyBuffer = bytes.NewBufferString(c.Param("type"))
	return nil
})

// 复合参数
e.GET("/books/{category:[a-z-]+}-{type}", func(c *elton.Context) error {
	c.BodyBuffer = bytes.NewBufferString(c.Param("category") + c.Param("type"))
	return nil
})

// 带中间件的路由配置
e.GET("/users/me", func(c *elton.Context) error {
	c.Set("account", "tree.xie")
	return c.Next()
}, func(c *elton.Context) error {
	c.BodyBuffer = bytes.NewBufferString(c.GetString("account"))
	return nil
})

中间件

简单方便的中间件机制,依赖各类定制的中间件,通过各类中间件的组合,方便快捷实现各类HTTP服务,简单介绍数据响应与出错处理的中间件。需要注意,elton中默认不会执行所有的中间件,每个中间件决定是否需要执行后续处理,如果需要则调用Next()函数,与gin不一样(gin默认为执行所有,若不希望执行后续的中间件,则调用Abort)。

responder

HTTP请求响应数据时,需要将数据转换为Buffer返回,而在应用时响应数据一般为各类的struct或map等结构化数据,因此elton提供了Body(interface{})字段来保存这些数据,再使用自定义的中间件将数据转换为对应的字节数据,elton-responder提供了将struct(map)转换为json字节并设置对应的Content-Type,对于string([]byte)则直接输出。

package main

import (
	"github.com/vicanso/elton"
	"github.com/vicanso/elton/middleware"
)

func main() {

	e := elton.New()
	// 对响应数据 c.Body 转换为相应的json响应
	e.Use(middleware.NewDefaultResponder())

	getSession := func(c *elton.Context) error {
		c.Set("account", "tree.xie")
		return c.Next()
	}
	e.GET("/users/me", getSession, func(c *elton.Context) (err error) {
		c.Body = &struct {
			Name string `json:"name"`
			Type string `json:"type"`
		}{
			c.GetString("account"),
			"vip",
		}
		return
	})

	err := e.ListenAndServe(":3000")
	if err != nil {
		panic(err)
	}
}
error

当请求处理失败时,直接返回error则可,elton从error中获取出错信息并输出。默认的出错处理并不适合实际应用场景,建议使用自定义出错类配合中间件,便于统一的错误处理,程序监控,下面是引入错误中间件将出错转换为json形式的响应。

package main

import (
	"github.com/vicanso/elton"
	"github.com/vicanso/elton/middleware"
	"github.com/vicanso/hes"
)

func main() {

	e := elton.New()
	// 指定出错以json的形式返回
	e.Use(middleware.NewError(middleware.ErrorConfig{
		ResponseType: "json",
	}))

	e.GET("/", func(c *elton.Context) (err error) {
		err = &hes.Error{
			StatusCode: 400,
			Category:   "users",
			Message:    "出错啦",
		}
		return
	})

	err := e.ListenAndServe(":3000")
	if err != nil {
		panic(err)
	}
}

更多的中间件可以参考middlewares

bench

goos: darwin
goarch: amd64
pkg: github.com/vicanso/elton
BenchmarkRoutes-8                        6925746               169.4 ns/op           120 B/op          2 allocs/op
BenchmarkGetFunctionName-8              136577900                9.265 ns/op           0 B/op          0 allocs/op
BenchmarkContextGet-8                   15311328                78.11 ns/op           16 B/op          1 allocs/op
BenchmarkContextNewMap-8                187684261                6.276 ns/op           0 B/op          0 allocs/op
BenchmarkConvertServerTiming-8           1484379               835.8 ns/op           360 B/op         11 allocs/op
BenchmarkGetStatus-8                    1000000000               0.2817 ns/op          0 B/op          0 allocs/op
BenchmarkFresh-8                          955664              1233 ns/op             416 B/op         10 allocs/op
BenchmarkStatic-8                          25128             46709 ns/op           20794 B/op        471 allocs/op
BenchmarkGitHubAPI-8                       14724             76190 ns/op           27175 B/op        609 allocs/op
BenchmarkGplusAPI-8                       326769              3659 ns/op            1717 B/op         39 allocs/op
BenchmarkParseAPI-8                       162340              6989 ns/op            3435 B/op         78 allocs/op
BenchmarkRWMutexSignedKeys-8            71757390                17.51 ns/op            0 B/op          0 allocs/op
BenchmarkAtomicSignedKeys-8             923771157                1.297 ns/op           0 B/op          0 allocs/op
PASS
ok      github.com/vicanso/elton        20.225s
goos: darwin
goarch: amd64
pkg: github.com/vicanso/elton/middleware
BenchmarkGenETag-8                        230718              4409 ns/op             160 B/op          6 allocs/op
BenchmarkMd5-8                            200134              5958 ns/op             120 B/op          6 allocs/op
BenchmarkNewShortHTTPHeader-8           10220961               116.4 ns/op            80 B/op          2 allocs/op
BenchmarkNewHTTPHeader-8                 4368654               277.1 ns/op            88 B/op          3 allocs/op
BenchmarkNewHTTPHeaders-8                 384062              2822 ns/op            1182 B/op         23 allocs/op
BenchmarkHTTPHeaderMarshal-8              225123              4664 ns/op            1344 B/op         21 allocs/op
BenchmarkToHTTPHeader-8                   296210              3834 ns/op            1272 B/op         34 allocs/op
BenchmarkHTTPHeaderUnmarshal-8            120136             10108 ns/op            1888 B/op         50 allocs/op
BenchmarkProxy-8                           13393             85170 ns/op           16031 B/op        104 allocs/op
PASS
ok      github.com/vicanso/elton/middleware     14.007s

Documentation

Overview

Radix tree implementation below is a based on the original work by Armon Dadgar in https://github.com/armon/go-radix/blob/master/radix.go (MIT licensed). It's been heavily modified for use as a HTTP routing tree.

Index

Constants

View Source
const (
	// ReuseContextEnabled resuse context enabled
	ReuseContextEnabled int32 = iota
	// ReuseContextDisabled reuse context disabled
	ReuseContextDisabled
)
View Source
const (
	// ErrCategory elton category
	ErrCategory = "elton"
	// HeaderXForwardedFor x-forwarded-for
	HeaderXForwardedFor = "X-Forwarded-For"
	// HeaderXRealIP x-real-ip
	HeaderXRealIP = "X-Real-Ip"
	// HeaderSetCookie Set-Cookie
	HeaderSetCookie = "Set-Cookie"
	// HeaderLocation Location
	HeaderLocation = "Location"
	// HeaderContentType Content-Type
	HeaderContentType = "Content-Type"
	// HeaderAuthorization Authorization
	HeaderAuthorization = "Authorization"
	// HeaderWWWAuthenticate WWW-Authenticate
	HeaderWWWAuthenticate = "WWW-Authenticate"
	// HeaderCacheControl Cache-Control
	HeaderCacheControl = "Cache-Control"
	// HeaderETag ETag
	HeaderETag = "ETag"
	// HeaderLastModified last modified
	HeaderLastModified = "Last-Modified"
	// HeaderContentEncoding content encoding
	HeaderContentEncoding = "Content-Encoding"
	// HeaderContentLength content length
	HeaderContentLength = "Content-Length"
	// HeaderIfModifiedSince if modified since
	HeaderIfModifiedSince = "If-Modified-Since"
	// HeaderIfNoneMatch if none match
	HeaderIfNoneMatch = "If-None-Match"
	// HeaderAcceptEncoding accept encoding
	HeaderAcceptEncoding = "Accept-Encoding"
	// HeaderServerTiming server timing
	HeaderServerTiming = "Server-Timing"
	// HeaderTransferEncoding transfer encoding
	HeaderTransferEncoding = "Transfer-Encoding"

	// MinRedirectCode min redirect code
	MinRedirectCode = 300
	// MaxRedirectCode max redirect code
	MaxRedirectCode = 308

	// MIMETextPlain text plain
	MIMETextPlain = "text/plain; charset=utf-8"
	// MIMEApplicationJSON application json
	MIMEApplicationJSON = "application/json; charset=utf-8"
	// MIMEBinary binary data
	MIMEBinary = "application/octet-stream"

	// Gzip gzip compress
	Gzip = "gzip"
	// Br brotli compress
	Br = "br"
	// Zstd zstd compress
	Zstd = "zstd"
)
View Source
const (
	// StatusRunning running status
	StatusRunning = iota
	// StatusClosing closing status
	StatusClosing
	// StatusClosed closed status
	StatusClosed
)
View Source
const (
	// SignedCookieSuffix signed cookie suffix
	SignedCookieSuffix = ".sig"
)

Variables

View Source
var (

	// ErrInvalidRedirect invalid redirect
	ErrInvalidRedirect = &hes.Error{
		StatusCode: 400,
		Message:    "invalid redirect",
		Category:   ErrCategory,
	}

	// ErrNilResponse nil response
	ErrNilResponse = &hes.Error{
		StatusCode: 500,
		Message:    "nil response",
		Category:   ErrCategory,
	}
	// ErrNotSupportPush not support http push
	ErrNotSupportPush = &hes.Error{
		StatusCode: 500,
		Message:    "not support http push",
		Category:   ErrCategory,
	}
	// ErrFileNotFound file not found
	ErrFileNotFound = &hes.Error{
		StatusCode: 404,
		Message:    "file not found",
		Category:   ErrCategory,
	}
)
View Source
var (
	// ServerTimingDur server timing dur
	ServerTimingDur = []byte(";dur=")
	// ServerTimingDesc server timing desc
	ServerTimingDesc = []byte(`;desc="`)
	// ServerTimingEnd server timing end
	ServerTimingEnd = []byte(`"`)
)
View Source
var DefaultTemplateParsers = NewTemplateParsers()
View Source
var (
	ErrSignKeyIsNil = hes.New("keys for sign cookie can't be nil")
)

Functions

func DefaultSkipper

func DefaultSkipper(c *Context) bool

DefaultSkipper default skipper function

func Fresh added in v1.4.1

func Fresh(reqHeader http.Header, resHeader http.Header) bool

Fresh returns fresh status by judget request header and response header

func GetClientIP

func GetClientIP(req *http.Request) string

GetClientIP returns the client ip of request, it will get ip from x-forwarded-for from request header and get the first public ip, if not exists then it will get ip from x-real-ip from request header, if not exists then it will use remote addr.

func GetRealIP

func GetRealIP(req *http.Request) string

GetRealIP returns the real ip of request, it will get ip from x-forwarded-for from request header, if not exists then it will get ip from x-real-ip from request header, if not exists then it will use remote addr.

func GetRemoteAddr

func GetRemoteAddr(req *http.Request) string

GetRemoteAddr returns the remote addr of request

func IsIntranet added in v1.2.5

func IsIntranet(ip string) bool

IsIntranet judges whether the ip is intranet

func NewMultipartForm added in v1.10.0

func NewMultipartForm() *multipartForm

NewMultipartForm returns a new multipart form, the form data will be saved as tmp file for less memory.

func ReadAllInitCap added in v1.8.2

func ReadAllInitCap(r io.Reader, initCap int) ([]byte, error)

copy from io.ReadAll ReadAll reads from r until an error or EOF and returns the data it read. A successful call returns err == nil, not err == EOF. Because ReadAll is defined to read from src until EOF, it does not treat an EOF from Read as an error to be reported.

func ReadAllToBuffer added in v1.8.4

func ReadAllToBuffer(r io.Reader, buffer *bytes.Buffer) error

ReadAllToBuffer reader from r util an error or EOF and write data to buffer. A successful call returns err == nil, not err == EOF. Because ReadAll is defined to read from src until EOF, it does not treat an EOF from Read as an error to be reported.

Types

type AtomicSignedKeys

type AtomicSignedKeys struct {
	// contains filtered or unexported fields
}

AtomicSignedKeys atomic toggle signed keys

func (*AtomicSignedKeys) GetKeys

func (atSk *AtomicSignedKeys) GetKeys() []string

GetKeys returns the key list of atomic signed keys

func (*AtomicSignedKeys) SetKeys

func (atSk *AtomicSignedKeys) SetKeys(values []string)

SetKeys sets the key list of atomic signed keys

type BeforeListener added in v1.8.4

type BeforeListener func(*Context)

BeforeListener before request handle listener

type BufferPool added in v1.8.4

type BufferPool interface {
	Get() *bytes.Buffer
	Put(*bytes.Buffer)
}

A BufferPool is an interface for getting and returning temporary buffer

func NewBufferPool added in v1.8.4

func NewBufferPool(initCap int) BufferPool

NewBufferPool creates a buffer pool, if the init cap gt 0, the buffer will be init with cap size

type Context

type Context struct {
	Request  *http.Request
	Response http.ResponseWriter
	// Committed commit the data to response, when it's true, the response has been sent.
	// If using custom response handler, please set it true.
	Committed bool
	// ID context id, using unique string function to generate it.
	ID string
	// Route route path, it's equal to the http router path with params.
	Route string
	// Next next function, it will be auto generated.
	Next func() error
	// Params route params
	Params *RouteParams
	// StatusCode http response's status code, default is 0 which will be handle as 200
	StatusCode int
	// Body http response's body, which should be converted to bytes by responder middleware.
	// JSON response middleware,  xml response middleware and so on.
	Body interface{}
	// BodyBuffer http response's body buffer, it should be set by responder middleware.
	BodyBuffer *bytes.Buffer
	// RequestBody http request body, which should be converted by request body parser middleware.
	RequestBody []byte
	// contains filtered or unexported fields
}

Context elton context

func NewContext

func NewContext(resp http.ResponseWriter, req *http.Request) *Context

NewContext return a new context

func (*Context) AddCookie

func (c *Context) AddCookie(cookie *http.Cookie)

AddCookie adds the cookie to the response

func (*Context) AddHeader

func (c *Context) AddHeader(key, value string)

AddHeader adds the key/value to response header. It appends to any existing value of the key.

func (*Context) AddRequestHeader

func (c *Context) AddRequestHeader(key, value string)

AddRequestHeader adds the key/value to http header. It appends to any existing value of the key.

func (*Context) AddSignedCookie

func (c *Context) AddSignedCookie(cookie *http.Cookie)

AddSignedCookie adds cookie to the response, it will also add a signed cookie

func (*Context) CacheMaxAge

func (c *Context) CacheMaxAge(age time.Duration, sMaxAge ...time.Duration)

CacheMaxAge sets `Cache-Control: public, max-age=MaxAge, s-maxage=SMaxAge` to the http response header. If sMaxAge is not empty, it will use the first duration as SMaxAge

func (*Context) ClientIP

func (c *Context) ClientIP() string

ClientIP returns the client ip of request, it will get ip from x-forwared-for from request header and get the first public ip, if not exists then it will get ip from x-real-ip from request header, if not exists then it will use remote addr.

func (*Context) Context added in v0.3.0

func (c *Context) Context() context.Context

Context returns context of request

func (*Context) Cookie

func (c *Context) Cookie(name string) (*http.Cookie, error)

Cookie return the cookie from http request

func (*Context) Created

func (c *Context) Created(body interface{})

Created sets the body to response and set the status to 201

func (*Context) Deadline added in v1.9.6

func (c *Context) Deadline() (deadline time.Time, ok bool)

func (*Context) DisableReuse

func (c *Context) DisableReuse()

DisableReuse sets the context disable reuse

func (*Context) Done added in v1.9.6

func (c *Context) Done() <-chan struct{}

func (*Context) Elton

func (c *Context) Elton() *Elton

Elton returns the elton instance of context

func (*Context) Err added in v1.9.6

func (c *Context) Err() error

func (*Context) Get

func (c *Context) Get(key interface{}) (interface{}, bool)

Get the value from context

func (*Context) GetBool added in v0.3.0

func (c *Context) GetBool(key interface{}) bool

GetBool returns bool value from context

func (*Context) GetDuration added in v0.3.0

func (c *Context) GetDuration(key interface{}) time.Duration

GetDuration returns duration from context

func (*Context) GetFloat32 added in v0.3.0

func (c *Context) GetFloat32(key interface{}) float32

GetFloat32 returns float32 value from context

func (*Context) GetFloat64 added in v0.3.0

func (c *Context) GetFloat64(key interface{}) float64

GetFloat64 returns float64 value from context

func (*Context) GetHeader

func (c *Context) GetHeader(key string) string

GetHeader return header value from http response

func (*Context) GetInt added in v0.3.0

func (c *Context) GetInt(key interface{}) int

GetInt returns int value from context

func (*Context) GetInt64 added in v0.3.0

func (c *Context) GetInt64(key interface{}) int64

GetInt64 returns int64 value from context

func (*Context) GetRequestHeader

func (c *Context) GetRequestHeader(key string) string

GetRequestHeader returns header value from http request

func (*Context) GetSignedCookie

func (c *Context) GetSignedCookie(name string) (*http.Cookie, int, error)

GetSignedCookie returns signed cookie from http request

func (*Context) GetString added in v0.3.0

func (c *Context) GetString(key interface{}) string

GetString returns string value from context

func (*Context) GetStringSlice added in v0.3.0

func (c *Context) GetStringSlice(key interface{}) []string

GetStringSlice returns string slice from context

func (*Context) GetTime added in v0.3.0

func (c *Context) GetTime(key interface{}) time.Time

GetTime returns time value from context

func (*Context) GetTrace added in v1.7.0

func (c *Context) GetTrace() *Trace

GetTrace get trace from context, if context without trace, new trace will be created.

func (*Context) HTML added in v1.5.0

func (c *Context) HTML(html string)

HTML sets content type and response body as html

func (*Context) Header

func (c *Context) Header() http.Header

Header returns headers of http response

func (*Context) IsReaderBody

func (c *Context) IsReaderBody() bool

IsReaderBody judgets whether body is reader

func (*Context) MergeHeader added in v1.1.1

func (c *Context) MergeHeader(h http.Header)

MergeHeader merges http header to response header

func (*Context) NewTrace added in v1.7.0

func (c *Context) NewTrace() *Trace

NewTrace returns a new trace and set it to context value

func (*Context) NoCache

func (c *Context) NoCache()

NoCache sets `Cache-Control: no-cache` to the http response header

func (*Context) NoContent

func (c *Context) NoContent()

NoContent clean all content and set status to 204

func (*Context) NoStore

func (c *Context) NoStore()

NoStore sets `Cache-Control: no-store` to the http response header

func (*Context) NotModified

func (c *Context) NotModified()

NotModified clean all content and set status to 304

func (*Context) Param

func (c *Context) Param(name string) string

Param returns the route param value

func (*Context) Pass

func (c *Context) Pass(another *Elton)

Pass request to another elton instance and set the context is committed

func (*Context) Pipe

func (c *Context) Pipe(r io.Reader) (int64, error)

Pipe the reader to the response

func (*Context) PrivateCacheMaxAge added in v1.4.0

func (c *Context) PrivateCacheMaxAge(age time.Duration)

PrivateCacheMaxAge sets `Cache-Control: private, max-age=MaxAge` to the response header.

func (*Context) Push

func (c *Context) Push(target string, opts *http.PushOptions) error

Push the target to http response

func (*Context) Query

func (c *Context) Query() map[string]string

Query returns the query map. It will return map[string]string, not the same as url.Values If want to get url.Values, use c.Request.URL.Query()

func (*Context) QueryParam

func (c *Context) QueryParam(name string) string

QueryParam returns the query param value

func (*Context) ReadFile added in v1.5.0

func (c *Context) ReadFile(key string) ([]byte, *multipart.FileHeader, error)

ReadFile reads file data from request

func (*Context) RealIP

func (c *Context) RealIP() string

RealIP returns the real ip of request, it will get ip from x-forwarded-for from request header, if not exists then it will get ip from x-real-ip from request header, if not exists then it will use remote addr.

func (*Context) Redirect

func (c *Context) Redirect(code int, url string) error

Redirect the http request to new location

func (*Context) RemoteAddr

func (c *Context) RemoteAddr() string

RemoteAddr returns the remote addr of request

func (*Context) Reset

func (c *Context) Reset()

Reset all fields of context

func (*Context) ResetHeader

func (c *Context) ResetHeader()

ResetHeader resets response header

func (*Context) SendFile added in v1.2.3

func (c *Context) SendFile(file string) error

SendFile to http response

func (*Context) ServerTiming added in v0.2.2

func (c *Context) ServerTiming(traceInfos TraceInfos, prefix string)

ServerTiming converts trace info to http response server timing

func (*Context) Set

func (c *Context) Set(key, value interface{})

Set the value to the context

func (*Context) SetContentTypeByExt

func (c *Context) SetContentTypeByExt(file string)

SetContentTypeByExt sets content type by file extname

func (*Context) SetHeader

func (c *Context) SetHeader(key, value string)

SetHeader sets the key/value to response header. It replaces any existing values of the key.

func (*Context) SetRequestHeader

func (c *Context) SetRequestHeader(key, value string)

SetRequestHeader sets http header to request. It replaces any existing values of the key.

func (*Context) SignedCookie

func (c *Context) SignedCookie(name string) (*http.Cookie, error)

SignedCookie returns signed cookie from http request

func (*Context) Value added in v1.9.6

func (c *Context) Value(key interface{}) interface{}

func (*Context) WithContext added in v0.3.0

func (c *Context) WithContext(ctx context.Context) *Context

WithContext changes the request to new request with context

func (*Context) Write

func (c *Context) Write(buf []byte) (int, error)

Write the response body

func (*Context) WriteHeader

func (c *Context) WriteHeader(statusCode int)

WriteHeader sets the http status code

type ContextKey added in v1.7.0

type ContextKey string
const ContextTraceKey ContextKey = "contextTrace"

type DoneListener added in v1.8.4

type DoneListener func(*Context)

DoneListener request done listener

type Elton

type Elton struct {
	// Server http server
	Server *http.Server
	// ErrorHandler set the function for error handler
	ErrorHandler ErrorHandler
	// NotFoundHandler set the function for not found handler
	NotFoundHandler http.HandlerFunc
	// MethodNotAllowedHandler set the function for method not allowed handler
	MethodNotAllowedHandler http.HandlerFunc
	// GenerateID generate id function, will use it to create context's id
	GenerateID GenerateID
	// EnableTrace enable trace
	EnableTrace bool
	// SignedKeys signed keys
	SignedKeys SignedKeysGenerator
	// contains filtered or unexported fields
}

Elton web framework instance

func New

func New() *Elton

New returns a new elton instance

func NewWithoutServer

func NewWithoutServer() *Elton

NewWithoutServer returns a new elton instance without http server

func (*Elton) ALL

func (e *Elton) ALL(path string, handlerList ...Handler) *Elton

ALL adds http all method handle

func (*Elton) AddGroup

func (e *Elton) AddGroup(groups ...*Group) *Elton

AddGroup adds the group to elton

func (*Elton) Close

func (e *Elton) Close() error

Close closes the http server

func (*Elton) Closing added in v1.2.2

func (e *Elton) Closing() bool

Closing judge the status whether is closing

func (*Elton) DELETE

func (e *Elton) DELETE(path string, handlerList ...Handler) *Elton

DELETE adds http delete method handle

func (*Elton) EmitError

func (e *Elton) EmitError(c *Context, err error) *Elton

EmitError emits an error event, it will call the listen functions of error event

func (*Elton) EmitTrace

func (e *Elton) EmitTrace(c *Context, infos TraceInfos) *Elton

EmitTrace emits a trace event, it will call the listen functions of trace event

func (*Elton) GET

func (e *Elton) GET(path string, handlerList ...Handler) *Elton

GET adds http get method handle

func (*Elton) GetFunctionName

func (e *Elton) GetFunctionName(fn interface{}) string

GetFunctionName return the name of handler function

func (*Elton) GetRouters added in v1.1.0

func (e *Elton) GetRouters() []RouterInfo

GetRouters returns routers of elton

func (*Elton) GetStatus

func (e *Elton) GetStatus() int32

GetStatus returns status of elton

func (*Elton) GracefulClose

func (e *Elton) GracefulClose(delay time.Duration) error

GracefulClose closes the http server graceful. It sets the status to be closing and delay to close.

func (*Elton) HEAD

func (e *Elton) HEAD(path string, handlerList ...Handler) *Elton

HEAD adds http head method handle

func (*Elton) Handle

func (e *Elton) Handle(method, path string, handlerList ...Handler) *Elton

Handle adds http handle function

func (*Elton) ListenAndServe

func (e *Elton) ListenAndServe(addr string) error

ListenAndServe listens the addr and serve http, it will throw panic if the server of elton is nil.

func (*Elton) ListenAndServeTLS added in v0.2.3

func (e *Elton) ListenAndServeTLS(addr, certFile, keyFile string) error

ListenAndServeTLS listens the addr and server https, it will throw panic if the server of elton is nil.

func (*Elton) Multi added in v1.9.4

func (e *Elton) Multi(methods []string, path string, handlerList ...Handler) *Elton

Multi adds multi method

func (*Elton) OPTIONS

func (e *Elton) OPTIONS(path string, handlerList ...Handler) *Elton

OPTIONS adds http options method handle

func (*Elton) OnBefore added in v1.8.4

func (e *Elton) OnBefore(ln BeforeListener) *Elton

OnBefore adds listen to before request done(after pre middlewares, before middlewares)

func (*Elton) OnDone added in v1.8.4

func (e *Elton) OnDone(ln DoneListener) *Elton

OnDone adds listen to request done, it will be triggered when the request handle is done

func (*Elton) OnError

func (e *Elton) OnError(ln ErrorListener) *Elton

OnError adds listen to error event

func (*Elton) OnTrace

func (e *Elton) OnTrace(ln TraceListener) *Elton

OnTrace adds listen to trace event

func (*Elton) PATCH

func (e *Elton) PATCH(path string, handlerList ...Handler) *Elton

PATCH adds http patch method handle

func (*Elton) POST

func (e *Elton) POST(path string, handlerList ...Handler) *Elton

POST adds http post method handle

func (*Elton) PUT

func (e *Elton) PUT(path string, handlerList ...Handler) *Elton

PUT adds http put method handle

func (*Elton) Pre

func (e *Elton) Pre(handlerList ...PreHandler) *Elton

Pre adds pre middleware function handler to elton's pre middleware list

func (*Elton) Running added in v1.2.2

func (e *Elton) Running() bool

Running judge the status whether is running

func (*Elton) Serve

func (e *Elton) Serve(l net.Listener) error

Serve serves http server, it will throw panic if the server of elton is nil.

func (*Elton) ServeHTTP

func (e *Elton) ServeHTTP(resp http.ResponseWriter, req *http.Request)

ServeHTTP http handler

func (*Elton) SetFunctionName

func (e *Elton) SetFunctionName(fn interface{}, name string)

SetFunctionName sets the name of handler function, it will use to http timing

func (*Elton) Shutdown added in v1.2.4

func (e *Elton) Shutdown() error

Shutdown shotdowns the http server

func (*Elton) TRACE

func (e *Elton) TRACE(path string, handlerList ...Handler) *Elton

TRACE adds http trace method handle

func (*Elton) Use

func (e *Elton) Use(handlerList ...Handler) *Elton

Use adds middleware handler function to elton's middleware list

func (*Elton) UseWithName added in v1.0.4

func (e *Elton) UseWithName(handler Handler, name string) *Elton

UseWithName adds middleware and set handler function's name

type EndpointHandler added in v0.4.1

type EndpointHandler func(c *Context)

type ErrorHandler

type ErrorHandler func(*Context, error)

ErrorHandler error handle function

type ErrorListener

type ErrorListener func(*Context, error)

ErrorListener error listener function

type GenerateID

type GenerateID func() string

GenerateID generate context id

type Group

type Group struct {
	Path        string
	HandlerList []Handler
	// contains filtered or unexported fields
}

Group group router

func NewGroup

func NewGroup(path string, handlerList ...Handler) *Group

NewGroup returns a new router group

func (*Group) ALL

func (g *Group) ALL(path string, handlerList ...Handler)

ALL adds http all methods handler to group

func (*Group) DELETE

func (g *Group) DELETE(path string, handlerList ...Handler)

DELETE adds http delete method handler to group

func (*Group) GET

func (g *Group) GET(path string, handlerList ...Handler)

GET adds http get method handler to group

func (*Group) HEAD

func (g *Group) HEAD(path string, handlerList ...Handler)

HEAD adds http head method handler to group

func (*Group) Multi added in v1.9.4

func (g *Group) Multi(methods []string, path string, handlerList ...Handler)

ALL adds http all methods handler to group

func (*Group) OPTIONS

func (g *Group) OPTIONS(path string, handlerList ...Handler)

OPTIONS adds http options method handler to group

func (*Group) PATCH

func (g *Group) PATCH(path string, handlerList ...Handler)

PATCH adds http patch method handler to group

func (*Group) POST

func (g *Group) POST(path string, handlerList ...Handler)

POST adds http post method handler to group

func (*Group) PUT

func (g *Group) PUT(path string, handlerList ...Handler)

PUT adds http put method handler to group

func (*Group) TRACE

func (g *Group) TRACE(path string, handlerList ...Handler)

TRACE adds http trace method handler to group

type HTMLTemplate added in v1.6.0

type HTMLTemplate struct {
	// contains filtered or unexported fields
}

func NewHTMLTemplate added in v1.6.0

func NewHTMLTemplate(read ReadFile) *HTMLTemplate

func (*HTMLTemplate) Render added in v1.6.0

func (ht *HTMLTemplate) Render(ctx context.Context, text string, data interface{}) (string, error)

Render renders the text using text/template

func (*HTMLTemplate) RenderFile added in v1.6.0

func (ht *HTMLTemplate) RenderFile(ctx context.Context, filename string, data interface{}) (string, error)

Render renders the text of file using text/template

type Handler

type Handler func(*Context) error

Handler elton handle function

func Compose

func Compose(handlerList ...Handler) Handler

Compose composes handler list as a handler

type PreHandler

type PreHandler func(*http.Request)

PreHandler pre handler

type RWMutexSignedKeys

type RWMutexSignedKeys struct {
	sync.RWMutex
	// contains filtered or unexported fields
}

RWMutexSignedKeys read/write mutex signed key

func (*RWMutexSignedKeys) GetKeys

func (rwSk *RWMutexSignedKeys) GetKeys() []string

GetKeys returns the key list of rwmutex signed keys

func (*RWMutexSignedKeys) SetKeys

func (rwSk *RWMutexSignedKeys) SetKeys(values []string)

SetKeys sets the key list of rwmutex signed keys

type ReadFile added in v1.6.0

type ReadFile func(filename string) ([]byte, error)

ReadFile defines how to read file

type RouteParams added in v0.4.1

type RouteParams struct {
	Keys, Values []string
	// contains filtered or unexported fields
}

RouteParams is a structure to track URL routing parameters efficiently.

func (*RouteParams) Add added in v0.4.1

func (s *RouteParams) Add(key, value string)

Add a URL parameter to the end of the route param

func (*RouteParams) Get added in v0.4.1

func (s *RouteParams) Get(key string) string

Get value from params

func (*RouteParams) Reset added in v0.4.3

func (s *RouteParams) Reset()

Reset the params

func (*RouteParams) ToMap added in v0.4.1

func (s *RouteParams) ToMap() map[string]string

ToMap converts route params to map[string]string

type Router

type Router struct {
	Method     string    `json:"method,omitempty"`
	Path       string    `json:"path,omitempty"`
	HandleList []Handler `json:"-"`
}

Router router

type RouterInfo

type RouterInfo struct {
	Method string `json:"method,omitempty"`
	Route  string `json:"route,omitempty"`
}

RouterInfo router's info

type SignedKeysGenerator

type SignedKeysGenerator interface {
	GetKeys() []string
	SetKeys([]string)
}

SignedKeysGenerator signed keys generator

type SimpleSignedKeys

type SimpleSignedKeys struct {
	// contains filtered or unexported fields
}

SimpleSignedKeys simple sigined key

func (*SimpleSignedKeys) GetKeys

func (sk *SimpleSignedKeys) GetKeys() []string

GetKeys returns the key list of simple signed keys

func (*SimpleSignedKeys) SetKeys

func (sk *SimpleSignedKeys) SetKeys(values []string)

SetKeys sets the key list of simple signed keys

type Skipper

type Skipper func(c *Context) bool

Skipper check for skip middleware

type TemplateParser added in v1.6.0

type TemplateParser interface {
	Render(ctx context.Context, text string, data interface{}) (string, error)
	RenderFile(ctx context.Context, filename string, data interface{}) (string, error)
}

type TemplateParsers added in v1.6.0

type TemplateParsers map[string]TemplateParser

func NewTemplateParsers added in v1.6.0

func NewTemplateParsers() TemplateParsers

func (TemplateParsers) Add added in v1.6.0

func (tps TemplateParsers) Add(template string, parser TemplateParser)

func (TemplateParsers) Get added in v1.6.0

func (tps TemplateParsers) Get(template string) TemplateParser

type Trace added in v1.7.0

type Trace struct {
	Infos TraceInfos
	// contains filtered or unexported fields
}

func GetTrace added in v1.7.0

func GetTrace(ctx context.Context) *Trace

GetTrace get trace from context, if context without trace, new trace will be created.

func NewTrace added in v1.7.0

func NewTrace() *Trace

NewTrace returns a new trace

func (*Trace) Add added in v1.7.0

func (t *Trace) Add(info *TraceInfo) *Trace

Add adds trace info to trace

func (*Trace) Calculate added in v1.7.0

func (t *Trace) Calculate()

Calculate calculates the duration of middleware

func (*Trace) Start added in v1.8.0

func (t *Trace) Start(name string) func()

Start starts a sub trace and return done function for sub trace.

type TraceInfo

type TraceInfo struct {
	Middleware bool          `json:"-"`
	Name       string        `json:"name,omitempty"`
	Duration   time.Duration `json:"duration,omitempty"`
}

TraceInfo trace's info

type TraceInfos

type TraceInfos []*TraceInfo

TraceInfos trace infos

func (TraceInfos) Filter added in v1.8.3

func (traceInfos TraceInfos) Filter(fn func(*TraceInfo) bool) TraceInfos

Filter filters the trace info, the new trace infos will be returned.

func (TraceInfos) FilterDurationGT added in v1.8.3

func (traceInfos TraceInfos) FilterDurationGT(d time.Duration) TraceInfos

FilterDurationGT flters the duration of trace is gt than d.

func (TraceInfos) ServerTiming

func (traceInfos TraceInfos) ServerTiming(prefix string) string

ServerTiming return server timing with prefix

type TraceListener

type TraceListener func(*Context, TraceInfos)

TraceListener trace listener

Directories

Path Synopsis
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL