yee

package module
v0.3.2 Latest Latest
Warning

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

Go to latest
Published: Apr 5, 2021 License: MIT Imports: 30 Imported by: 0

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

Quick start
 	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")
API

Provide GET POST PUT DELETE HEAD OPTIONS TRACE PATCH

    
  y := yee.New()
    
  y.GET("/someGet", handler)
  y.POST("/somePost", handler)
  y.PUT("/somePut", handler)
  y.DELETE("/someDelete", handler)
  y.PATCH("/somePatch", handler)
  y.HEAD("/someHead", handler)
  y.OPTIONS("/someOptions", handler)
    
  y.Run(":8000")
    
Restful

You can use Any & Restful method to implement your restful api

  • Any
  y := yee.New()
    
  y.Any("/any", handler)
    
  y.Run(":8000")

  // All request methods for the same URL use the same handler

  • Restful

  func userUpdate(c Context) (err error) {
  	return c.String(http.StatusOK, "updated")
  }
  
  func userFetch(c Context) (err error) {
  	return c.String(http.StatusOK, "get it")
  }
  
  func RestfulApi() yee.RestfulApi {
  	return RestfulApi{
  		Get:  userFetch,
  		Post: userUpdate,
  	}
  }
  
  y := New()
  
  y.Restful("/", testRestfulApi())
  
  y.Run(":8000")
 
// All request methods for the same URL use the different handler

 

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"
)

Header types

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 (
	Critical = iota
	Error
	Warning
	Info
	Debug
)

logger types

View Source
const PREFIX = `` /* 815-byte string literal not displayed */

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")
	ErrNotFoundHandler        = errors.New("404 NOT FOUND")
	ErrInvalidCertOrKeyType   = errors.New("invalid cert or key type, must be string or []byte")
)

Err types

View Source
var FinderPrefix = `
type FinderPrefix struct {
    Valve   bool   // 自行添加tag
	${FINDER_EXPR}
}
`
View Source
var QueryExprPrefix = `` /* 150-byte string literal not displayed */

Functions

func BytesToString

func BytesToString(b []byte) string

BytesToString converts byte slice to string without a memory allocation.

func GenQueryExpr

func GenQueryExpr(QueryExpr []expr) (string, string, string)

func GenerateRestfulAPI

func GenerateRestfulAPI(GenCodeVal GenCodeVal) string

func LogCreator

func LogCreator() *logger

LogCreator ...

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)
	File(file string) 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()
}

Context is the default implementation interface of context

type Core

type Core struct {
	*Router

	HandleMethodNotAllowed bool
	H2server               *http.Server

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

Core implement httpServer interface

func C

func C() *Core

func CBasePath

func CBasePath(basePath string) *Core

func New

func New() *Core

New create a core and perform a series of initializations

func NewAndSetBasePath

func NewAndSetBasePath(basePath string) *Core

func (*Core) NewContext

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

NewContext is for testing

func (*Core) Run

func (c *Core) Run(addr string)

Run is launch of http

func (*Core) RunH2C

func (c *Core) RunH2C(addr string)

RunH2C is launch of h2c 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

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

RunTLS is launch of tls 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

func (c *Core) SetLogLevel(l uint8)

SetLogLevel define custom log level

func (*Core) Use

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

Use defines which middleware is uesd when we dose not match prefix or method we`ll register noRoute or noMethod handle for this otherwise, we cannot be verified for noRoute/noMethod

type DefaultBinder

type DefaultBinder struct{}

DefaultBinder is the default implementation of the Binder interface.

func (*DefaultBinder) Bind

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

Bind implements the `Binder#Bind` function.

type GenCodeVal

type GenCodeVal struct {
	Flag      string `json:"flag"`       // 根据哪个字段进行CURD
	Package   string `json:"package"`    // 项目名,根据项目名生成package name
	QueryExpr []expr `json:"query_expr"` // 查询条件
	Page      string `json:"page"`       //分页大小
	Modal     string `json:"modal"`
}

type HandlerFunc

type HandlerFunc func(Context) (err error)

HandlerFunc define handler of context

type HandlersChain

type HandlersChain []HandlerFunc

HandlersChain define handler chain of context

type Logger

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

Logger ...

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 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 RestfulAPI

type RestfulAPI struct {
	Get    HandlerFunc
	Post   HandlerFunc
	Delete HandlerFunc
	Put    HandlerFunc
}

RestfulAPI is the default implementation of restfulApi interface

type Router

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

func (*Router) Any

func (r *Router) Any(path string, handler ...HandlerFunc)

func (*Router) DELETE

func (r *Router) DELETE(path string, handler ...HandlerFunc)

func (*Router) GET

func (r *Router) GET(path string, handler ...HandlerFunc)

func (*Router) Group

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

func (*Router) HEAD

func (r *Router) HEAD(path string, handler ...HandlerFunc)

func (*Router) OPTIONS

func (r *Router) OPTIONS(path string, handler ...HandlerFunc)

func (*Router) PATCH

func (r *Router) PATCH(path string, handler ...HandlerFunc)

func (*Router) POST

func (r *Router) POST(path string, handler ...HandlerFunc)

func (*Router) PUT

func (r *Router) PUT(path string, handler ...HandlerFunc)

func (*Router) Packr

func (r *Router) Packr(relativePath string, fs http.FileSystem)

func (*Router) Restful

func (r *Router) Restful(path string, api RestfulAPI)

func (*Router) Static

func (r *Router) Static(relativePath, root string)

func (*Router) TRACE

func (r *Router) TRACE(path string, handler ...HandlerFunc)

func (*Router) Use

func (r *Router) Use(middleware ...HandlerFunc)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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