yee

package module
v0.0.9 Latest Latest
Warning

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

Go to latest
Published: Jun 19, 2020 License: MIT Imports: 30 Imported by: 3

README

Yee

 

🦄 Web frameworks for Go, easier & faster.

This is a framework for learning purposes. Refer to the code for Echo and Gin

  • Faster HTTP router
  • Build RESTful APIs
  • Group APIs
  • Extensible middleware framework
  • Define middleware at root, group or route level
  • Data binding for JSON, XML and form payload
  • HTTP/2(H2C) support

Supported Go versions

Yee is available as a Go module. You need to use Go 1.13 +

Example

 	y := yee.New()

 	y.Static("/assets", "dist/assets")

	y.GET("/", func(c yee.Context) (err error) {
		return c.HTMLTml(http.StatusOK, "dist/index.html")
	})

 	y.GET("/hello", func(c yee.Context) error {
		return c.String(http.StatusOK, "<h1>Hello Gee</h1>")
	})

	y.POST("/test", func(c yee.Context) (err error) {
		u := new(p)
		if err := c.Bind(u); err != nil {
			return c.JSON(http.StatusOK, err.Error())
		}
		return c.JSON(http.StatusOK, u.Test)
	})

        y.Run(":9000")

Middleware

  • basic auth
  • cors
  • crfs
  • gzip
  • jwt
  • logger
  • rate limit
  • recovery
  • secure
  • request id

Benchmark

Resource

  • CPU: i7-9750H
  • Memory: 16G
  • OS: macOS 10.15.5

Date: 2020/06/17

License

MIT

Documentation

Index

Constants

View Source
const (
	HeaderAccept              = "Accept"
	HeaderAcceptEncoding      = "Accept-Encoding"
	HeaderAuthorization       = "Authorization"
	HeaderContentDisposition  = "Content-Disposition"
	HeaderContentEncoding     = "Content-Encoding"
	HeaderContentLength       = "Content-Length"
	HeaderContentType         = "Content-Type"
	HeaderCookie              = "Cookie"
	HeaderSetCookie           = "Set-Cookie"
	HeaderIfModifiedSince     = "If-Modified-Since"
	HeaderLastModified        = "Last-Modified"
	HeaderLocation            = "Location"
	HeaderUpgrade             = "Upgrade"
	HeaderVary                = "Vary"
	HeaderWWWAuthenticate     = "WWW-Authenticate"
	HeaderXForwardedFor       = "X-Forwarded-For"
	HeaderXForwardedProto     = "X-Forwarded-Proto"
	HeaderXForwardedProtocol  = "X-Forwarded-Protocol"
	HeaderXForwardedSsl       = "X-Forwarded-Ssl"
	HeaderXUrlScheme          = "X-Url-Scheme"
	HeaderXHTTPMethodOverride = "X-HTTP-Method-Override"
	HeaderXRealIP             = "X-Real-IP"
	HeaderXRequestID          = "X-Request-ID"
	HeaderXRequestedWith      = "X-Requested-With"
	HeaderServer              = "Server"
	HeaderOrigin              = "Origin"

	// Access control
	HeaderAccessControlRequestMethod    = "Access-Control-Request-Method"
	HeaderAccessControlRequestHeaders   = "Access-Control-Request-Headers"
	HeaderAccessControlAllowOrigin      = "Access-Control-Allow-Origin"
	HeaderAccessControlAllowMethods     = "Access-Control-Allow-Methods"
	HeaderAccessControlAllowHeaders     = "Access-Control-Allow-Headers"
	HeaderAccessControlAllowCredentials = "Access-Control-Allow-Credentials"
	HeaderAccessControlExposeHeaders    = "Access-Control-Expose-Headers"
	HeaderAccessControlMaxAge           = "Access-Control-Max-Age"

	// Security
	HeaderStrictTransportSecurity         = "Strict-Transport-Security"
	HeaderXContentTypeOptions             = "X-Content-Type-Options"
	HeaderXXSSProtection                  = "X-XSS-Protection"
	HeaderXFrameOptions                   = "X-Frame-Options"
	HeaderContentSecurityPolicy           = "Content-Security-Policy"
	HeaderContentSecurityPolicyReportOnly = "Content-Security-Policy-Report-Only"
	HeaderXCSRFToken                      = "X-CSRF-Token"
	HeaderReferrerPolicy                  = "Referrer-Policy"
)
View Source
const (
	MIMEApplicationJSON                  = "application/json"
	MIMEApplicationJSONCharsetUTF8       = MIMEApplicationJSON + "; " + charsetUTF8
	MIMEApplicationJavaScript            = "application/javascript"
	MIMEApplicationJavaScriptCharsetUTF8 = MIMEApplicationJavaScript + "; " + charsetUTF8
	MIMEApplicationXML                   = "application/xml"
	MIMEApplicationXMLCharsetUTF8        = MIMEApplicationXML + "; " + charsetUTF8
	MIMETextXML                          = "text/xml"
	MIMETextXMLCharsetUTF8               = MIMETextXML + "; " + charsetUTF8
	MIMEApplicationForm                  = "application/x-www-form-urlencoded"
	MIMEApplicationProtobuf              = "application/protobuf"
	MIMEApplicationMsgpack               = "application/msgpack"
	MIMETextHTML                         = "text/html"
	MIMETextHTMLCharsetUTF8              = MIMETextHTML + "; " + charsetUTF8
	MIMETextPlain                        = "text/plain"
	MIMETextPlainCharsetUTF8             = MIMETextPlain + "; " + charsetUTF8
	MIMEMultipartForm                    = "multipart/form-data"
	MIMEOctetStream                      = "application/octet-stream"
)

MIME types

View Source
const (
	Uppercase    = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
	Lowercase    = "abcdefghijklmnopqrstuvwxyz"
	Alphabetic   = Uppercase + Lowercase
	Numeric      = "0123456789"
	Alphanumeric = Alphabetic + Numeric
)
View Source
const (
	Critical = iota
	Error
	Warning
	Info
	Debug
)
View Source
const Version = "v0.0.1"

Variables

View Source
var (
	ErrUnsupportedMediaType   = errors.New("http server not support media type")
	ErrValidatorNotRegistered = errors.New("validator not registered")
	ErrRendererNotRegistered  = errors.New("renderer not registered")
	ErrInvalidRedirectCode    = errors.New("invalid redirect status code")
	ErrCookieNotFound         = errors.New("cookie not found")
	ErrInvalidCertOrKeyType   = errors.New("invalid cert or key type, must be string or []byte")
)

Functions

func BytesToString

func BytesToString(b []byte) string

BytesToString converts byte slice to string without a memory allocation.

func LogCreator

func LogCreator() *logger

func RandomString added in v0.0.6

func RandomString(length uint8, charsets ...string) string

func StringToBytes

func StringToBytes(s string) (b []byte)

StringToBytes converts string to byte slice without a memory allocation.

Types

type BindUnmarshaler

type BindUnmarshaler interface {
	// UnmarshalParam decodes and assigns a value from an form or query param.
	UnmarshalParam(param string) error
}

BindUnmarshaler is the interface used to wrap the UnmarshalParam method. Types that don't implement this, but do implement encoding.TextUnmarshaler will use that interface instead.

type Context

type Context interface {
	Request() *http.Request
	Response() ResponseWriter
	HTML(code int, html string) (err error)
	JSON(code int, i interface{}) error
	String(code int, s string) error
	Status(code int)
	QueryParam(name string) string
	QueryString() string
	SetHeader(key string, value string)
	AddHeader(key string, value string)
	GetHeader(key string) string
	FormValue(name string) string
	FormParams() (url.Values, error)
	FormFile(name string) (*multipart.FileHeader, error)
	MultipartForm() (*multipart.Form, error)
	Redirect(code int, uri string) error
	Params(name string) string
	RequestURI() string
	Scheme() string
	IsTls() bool
	Next()
	HTMLTml(code int, tml string) (err error)
	QueryParams() map[string][]string
	Bind(i interface{}) error
	Cookie(name string) (*http.Cookie, error)
	SetCookie(cookie *http.Cookie)
	Cookies() []*http.Cookie
	Get(key string) interface{}
	Put(key string, values interface{})
	ServerError(code int, defaultMessage string) error
	RemoteIp() string
	Logger() Logger
	Reset()
}

type Core

type Core struct {
	HandleMethodNotAllowed bool
	H2server               *http.Server

	RedirectTrailingSlash bool
	RedirectFixedPath     bool
	Banner                bool
	// contains filtered or unexported fields
}

Core implement httpServer interface

func New

func New() *Core

func (Core) DELETE

func (r Core) DELETE(path string, handler ...HandlerFunc)

func (Core) GET

func (r Core) GET(path string, handler ...HandlerFunc)

func (Core) Group

func (r Core) Group(prefix string, handlers ...HandlerFunc) *router

func (Core) HEAD

func (r Core) HEAD(path string, handler ...HandlerFunc)

func (*Core) NewContext added in v0.0.6

func (c *Core) NewContext(r *http.Request, w http.ResponseWriter) Context

the func is for testing

func (Core) OPTIONS

func (r Core) OPTIONS(path string, handler ...HandlerFunc)

func (Core) PATCH

func (r Core) PATCH(path string, handler ...HandlerFunc)

func (Core) POST

func (r Core) POST(path string, handler ...HandlerFunc)

func (Core) PUT

func (r Core) PUT(path string, handler ...HandlerFunc)

func (*Core) Run added in v0.0.6

func (c *Core) Run(addr string)

func (*Core) RunH2C added in v0.0.6

func (c *Core) RunH2C(addr string)

In normal conditions, http2 must used certificate H2C is non-certificate`s http2 notes: 1.the browser is not supports H2C proto, you should write your web client test program 2.the H2C protocol is not safety

func (*Core) RunTLS added in v0.0.6

func (c *Core) RunTLS(addr, certFile, keyFile string)

golang supports http2,if client supports http2 Otherwise, the http protocol return to http1.1

func (*Core) ServeHTTP

func (c *Core) ServeHTTP(w http.ResponseWriter, r *http.Request)

func (*Core) SetLogLevel added in v0.0.6

func (c *Core) SetLogLevel(l uint8)

func (Core) Static

func (r Core) Static(relativePath, root string)

func (Core) TRACE added in v0.0.5

func (r Core) TRACE(path string, handler ...HandlerFunc)

func (*Core) Use

func (c *Core) Use(middleware ...HandlerFunc)

type DefaultBinder

type DefaultBinder struct{}

Binder is the interface that wraps the Bind method. DefaultBinder is the default implementation of the Binder interface.

func (*DefaultBinder) Bind added in v0.0.6

func (b *DefaultBinder) Bind(i interface{}, c Context) (err error)

Bind implements the `Binder#Bind` function.

type HandlerFunc

type HandlerFunc func(Context) (err error)

type HandlersChain

type HandlersChain []HandlerFunc

type Logger

type Logger interface {
	Critical(msg string)
	Error(msg string)
	Warn(msg string)
	Info(msg string)
	Debug(msg string)
	SetLevel(level uint8)
}

type Param

type Param struct {
	Key   string
	Value string
}

Param is a single URL parameter, consisting of a key and a value.

type Params

type Params []Param

Params is a Param-slice, as returned by the router. The slice is ordered, the first URL parameter is also the first slice value. It is therefore safe to read values by the index.

func (Params) ByName

func (ps Params) ByName(name string) (va string)

ByName returns the value of the first Param which key matches the given name. If no matching Param is found, an empty string is returned.

func (Params) Get

func (ps Params) Get(name string) (string, bool)

Get returns the value of the first Param which key matches the given name. If no matching Param is found, an empty string is returned.

type Random added in v0.0.6

type Random struct{}

func RandomInit added in v0.0.6

func RandomInit() *Random

func (*Random) String added in v0.0.6

func (r *Random) String(length uint8, charsets ...string) string

type ResponseWriter

type ResponseWriter interface {
	http.ResponseWriter
	http.Hijacker
	http.Flusher
	http.CloseNotifier

	// Returns the HTTP response status code of the current request.
	Status() int

	// Returns the number of bytes already written into the response http body.
	// See Written()
	Size() int

	// Writes the string into the response body.
	WriteString(string) (int, error)

	// Returns true if the response body was already written.
	Written() bool

	//// Forces to write the http header (status code + headers).
	WriteHeaderNow()

	// get the http.Pusher for server push
	Pusher() http.Pusher

	Writer() http.ResponseWriter

	Override(rw http.ResponseWriter)
}

ResponseWriter ...

type YeeConfig added in v0.0.6

type YeeConfig struct {
	Banner bool
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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