yee

package module
v0.5.1 Latest Latest
Warning

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

Go to latest
Published: Dec 18, 2023 License: MIT Imports: 33 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 URI Query, JSON, XML, Protocol Buffer3 and form payload
  • HTTP/2(H2C)/Http3(QUIC) support

Supported Go versions

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

Example

Quick start
	file, err := os.OpenFile("logrus.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
	
	if err != nil {
	    return
	}
	
	y := yee.New()
	
	y.SetLogLevel(logger.Warning)
	
	y.SetLogOut(file)
	 
	y.Use(Logger())
	 
 	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"
	HeaderConnection          = "Connection"
	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 DefaultPrefix = "/debug/pprof"
View Source
const PREFIX = `` /* 816-byte string literal not displayed */
View Source
const (
	StatusCodeContextCanceled = 499
)

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 Dir added in v0.3.0

func Dir(root string, listDirectory bool) http.FileSystem

Dir returns a http.FileSystem that can be used by http.FileServer(). It is used internally in router.Static(). if listDirectory == true, then it works the same as http.Dir() otherwise it returns a filesystem that prevents http.FileServer() to list the directory files.

func GenQueryExpr added in v0.2.0

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

func GenerateRestfulAPI added in v0.2.0

func GenerateRestfulAPI(GenCodeVal GenCodeVal) 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
	SetRequest(r *http.Request)
	Response() ResponseWriter
	SetResponse(w ResponseWriter)
	HTML(code int, html string) (err error)
	JSON(code int, i interface{}) error
	ProtoBuf(code int, i proto.Message) error
	String(code int, s string) error
	FormValue(name string) string
	FormParams() (url.Values, error)
	FormFile(name string) (*multipart.FileHeader, error)
	File(file string) error
	Blob(code int, contentType string, b []byte) (err error)
	Status(code int)
	QueryParam(name string) string
	QueryString() string
	SetHeader(key string, value string)
	AddHeader(key string, value string)
	GetHeader(key string) string
	MultipartForm() (*multipart.Form, error)
	Redirect(code int, uri string) error
	Params(name string) string
	RequestURI() string
	Scheme() string
	IsTLS() bool
	IsWebsocket() bool
	Next()
	HTMLTpl(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.Logger
	Reset()
	Crash()
	IsCrash() bool
	CrashWithStatus(code int)
	CrashWithJson(code int, json interface{})
	Path() string
	Abort()
}

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 added in v0.1.8

func C() *Core

func New

func New() *Core

New create a core and perform a series of initializations

func (*Core) NewContext added in v0.0.6

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

NewContext is for testing

func (*Core) Pprof added in v0.3.1

func (c *Core) Pprof()

func (*Core) Run added in v0.0.6

func (c *Core) Run(addr string)

Run is launch of http

func (*Core) RunH2C added in v0.0.6

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 added in v0.0.6

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 added in v0.0.6

func (c *Core) SetLogLevel(l uint8)

SetLogLevel define custom log level

func (*Core) SetLogOut added in v0.2.8

func (c *Core) SetLogOut(out io.Writer)

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 added in v0.0.6

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

type GenCodeVal added in v0.2.0

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

func WrapF added in v0.3.1

func WrapF(f http.HandlerFunc) HandlerFunc

func WrapH added in v0.3.1

func WrapH(h http.Handler) HandlerFunc

type HandlersChain

type HandlersChain []HandlerFunc

HandlersChain define handler chain of context

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 added in v0.1.2

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

RestfulAPI is the default implementation of restfulApi interface

type Router added in v0.1.4

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

func (*Router) Any added in v0.1.4

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

func (*Router) DELETE added in v0.1.4

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

func (*Router) GET added in v0.1.4

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

func (*Router) Group added in v0.1.4

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

func (*Router) HEAD added in v0.1.4

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

func (*Router) OPTIONS added in v0.1.4

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

func (*Router) PATCH added in v0.1.4

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

func (*Router) POST added in v0.1.4

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

func (*Router) PUT added in v0.1.4

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

func (*Router) Pack added in v0.3.0

func (r *Router) Pack(relativePath string, f embed.FS, root string)

func (*Router) Restful added in v0.1.4

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

func (*Router) Static added in v0.1.4

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

func (*Router) TRACE added in v0.1.4

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

func (*Router) Use added in v0.1.4

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