jin

package module
v0.0.0-...-0f24b23 Latest Latest
Warning

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

Go to latest
Published: Sep 20, 2023 License: MIT Imports: 23 Imported by: 1

README

Jǐn

瑾,瑾瑜,美玉也。

Jin is a HTTP web framework written in Go (Golang) with a slim core but limitless extensibility.

Feature

  • Middleware support
  • Dependency injection
  • Integrate non-intrusively

Performance

Due to the speed of reflect.Call, every inject process will take about 200ns, which means if the handler in handler-chain didn't support fast-invoke will take about 200ns for dependency inject (on mac m2).

Status

Alpha. Expect API changes and bug fixes.

License

MIT

Documentation

Index

Constants

View Source
const (
	// DebugMode indicates Jin mode is debug.
	DebugMode = "debug"
	// ReleaseMode indicates Jin mode is release.
	ReleaseMode = "release"
	// TestMode indicates Jin mode is test.
	TestMode = "test"
)
View Source
const EnvJinMode = "JIN_MODE"

EnvJinMode indicates environment name for Jin mode.

Variables

View Source
var DebugPrintRouteFunc func(httpMethod, absolutePath, handlerName string, nuHandlers int)

DebugPrintRouteFunc indicates debug log output format.

View Source
var DefaultErrorWriter io.Writer = os.Stderr

DefaultErrorWriter is the default io.Writer used by Jin to debug errors

View Source
var DefaultWriter io.Writer = os.Stdout

DefaultWriter is the default io.Writer used by Jin for debug output and middleware output like Logger() or Recovery(). Note that both Logger and Recovery provides custom ways to configure their output io.Writer. To support coloring in Windows use:

import "github.com/mattn/go-colorable"
jin.DefaultWriter = colorable.NewColorableStdout()

Functions

func IsDebugging

func IsDebugging() bool

func Mode

func Mode() string

Mode returns current Jin mode.

func SetMode

func SetMode(value string)

SetMode sets gin mode according to input string.

Types

type Context

type Context struct {
	inject.Injector

	Request *http.Request
	Writer  ResponseWriter
	Params  Params
	// contains filtered or unexported fields
}

func (*Context) Abort

func (c *Context) Abort()

Abort prevents pending handlers from being called. Note that this will not stop the current handler. Let's say you have an authorization middleware that validates that the current request is authorized. If the authorization fails (ex: the password does not match), call Abort to ensure the remaining handlers for this request are not called.

func (*Context) FullPath

func (c *Context) FullPath() string

FullPath returns a matched route full path. For not found routes returns an empty string.

router.GET("/user/:id", func(c *gin.Context) {
    c.FullPath() == "/user/:id" // true
})

func (*Context) IsAborted

func (c *Context) IsAborted() bool

IsAborted returns true if the current context was aborted.

func (*Context) Next

func (c *Context) Next()

Next should be used only inside middleware. It executes the pending handlers in the chain inside the calling handler. See example in GitHub.

type ContextInvoker

type ContextInvoker func(ctx *Context)

ContextInvoker is an inject.FastInvoker implementation of `func(Context)`.

func (ContextInvoker) Invoke

func (invoke ContextInvoker) Invoke(args []interface{}) ([]reflect.Value, error)

type Engine

type Engine struct {
	inject.Injector
	RouterGroup

	// RedirectTrailingSlash enables automatic redirection if the current route can't be matched but a
	// handler for the path with (without) the trailing slash exists.
	// For example if /foo/ is requested but a route only exists for /foo, the
	// client is redirected to /foo with http status code 301 for GET requests
	// and 307 for all other request methods.
	RedirectTrailingSlash bool

	// RedirectFixedPath if enabled, the router tries to fix the current request path, if no
	// handle is registered for it.
	// First superfluous path elements like ../ or // are removed.
	// Afterwards the router does a case-insensitive lookup of the cleaned path.
	// If a handle can be found for this route, the router makes a redirection
	// to the corrected path with status code 301 for GET requests and 307 for
	// all other request methods.
	// For example /FOO and /..//Foo could be redirected to /foo.
	// RedirectTrailingSlash is independent of this option.
	RedirectFixedPath bool

	// HandleMethodNotAllowed if enabled, the router checks if another method is allowed for the
	// current route, if the current request can not be routed.
	// If this is the case, the request is answered with 'Method Not Allowed'
	// and HTTP status code 405.
	// If no other Method is allowed, the request is delegated to the NotFound
	// handler.
	HandleMethodNotAllowed bool

	// UseRawPath if enabled, the url.RawPath will be used to find parameters.
	UseRawPath bool

	// UnescapePathValues if true, the path value will be unescaped.
	// If UseRawPath is false (by default), the UnescapePathValues effectively is true,
	// as url.Path going to be used, which is already unescaped.
	UnescapePathValues bool

	// RemoveExtraSlash a parameter can be parsed from the URL even with extra slashes.
	// See the PR #1817 and issue #1644
	RemoveExtraSlash bool

	// UseH2C enable h2c support.
	UseH2C bool
	// contains filtered or unexported fields
}

func Default

func Default() *Engine

Default returns an Engine instance with the Logger and Recovery middleware already attached.

func New

func New() *Engine

func (*Engine) Handler

func (engine *Engine) Handler() http.Handler

func (*Engine) NoMethod

func (engine *Engine) NoMethod(handlers ...HandlerFunc)

NoMethod sets the handlers called when Engine.HandleMethodNotAllowed = true.

func (*Engine) NoRoute

func (engine *Engine) NoRoute(handlers ...HandlerFunc)

NoRoute adds handlers for NoRoute. It returns a 404 code by default.

func (*Engine) Run

func (engine *Engine) Run(addr ...string) (err error)

Run attaches the router to a http.Server and starts listening and serving HTTP requests. It is a shortcut for http.ListenAndServe(addr, router) Note: this method will block the calling goroutine indefinitely unless an error happens.

func (*Engine) ServeHTTP

func (engine *Engine) ServeHTTP(w http.ResponseWriter, req *http.Request)

ServeHTTP conforms to the http.Handler interface.

func (*Engine) Use

func (engine *Engine) Use(middleware ...HandlerFunc) IRoutes

Use attaches a global middleware to the router. i.e. the middleware attached through Use() will be included in the handlers chain for every single request. Even 404, 405, static files... For example, this is the right place for a logger or error management middleware.

type HandlerFunc

type HandlerFunc interface{}

HandlerFunc defines the handler used by Jin middleware as return value.

func Recovery

func Recovery() HandlerFunc

Recovery returns a middleware handler that recovers from any panics and writes a 500 status code to the response if there was one. While in development mode (EnvTypeDev), Recovery will also output the panic as HTML.

type HandlersChain

type HandlersChain []HandlerFunc

HandlersChain defines a HandlerFunc slice.

func (HandlersChain) Last

func (c HandlersChain) Last() HandlerFunc

Last returns the last handler in the chain. i.e. the last handler is the main one.

type IRouter

type IRouter interface {
	IRoutes
	Group(string, ...HandlerFunc) *RouterGroup
}

IRouter defines all router handle interface includes single and group router.

type IRoutes

type IRoutes interface {
	Use(middleware ...HandlerFunc) IRoutes

	Handle(method string, relativePath string, handlers ...HandlerFunc) IRoutes
	Any(relativePath string, handlers ...HandlerFunc) IRoutes
	GET(relativePath string, handlers ...HandlerFunc) IRoutes
	POST(relativePath string, handlers ...HandlerFunc) IRoutes
	DELETE(relativePath string, handlers ...HandlerFunc) IRoutes
	PATCH(relativePath string, handlers ...HandlerFunc) IRoutes
	PUT(relativePath string, handlers ...HandlerFunc) IRoutes
	OPTIONS(relativePath string, handlers ...HandlerFunc) IRoutes
	HEAD(relativePath string, handlers ...HandlerFunc) IRoutes
	Match(methods []string, relativePath string, handlers ...HandlerFunc) IRoutes
}

IRoutes defines all router handle interface.

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 and a boolean true. If no matching Param is found, an empty string is returned and a boolean false .

type ResponseWriter

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

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

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

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

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

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

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

type RouterGroup

type RouterGroup struct {
	Handlers HandlersChain
	// contains filtered or unexported fields
}

RouterGroup is used internally to configure router, a RouterGroup is associated with a prefix and an array of handlers (middleware).

func (*RouterGroup) Any

func (group *RouterGroup) Any(relativePath string, handlers ...HandlerFunc) IRoutes

Any registers a route that matches all the HTTP methods. GET, POST, PUT, PATCH, HEAD, OPTIONS, DELETE, CONNECT, TRACE.

func (*RouterGroup) BasePath

func (group *RouterGroup) BasePath() string

BasePath returns the base path of router group. For example, if v := router.Group("/rest/n/v1/api"), v.BasePath() is "/rest/n/v1/api".

func (*RouterGroup) DELETE

func (group *RouterGroup) DELETE(relativePath string, handlers ...HandlerFunc) IRoutes

DELETE is a shortcut for router.Handle("DELETE", path, handlers).

func (*RouterGroup) GET

func (group *RouterGroup) GET(relativePath string, handlers ...HandlerFunc) IRoutes

GET is a shortcut for router.Handle("GET", path, handlers).

func (*RouterGroup) Group

func (group *RouterGroup) Group(relativePath string, handlers ...HandlerFunc) *RouterGroup

Group creates a new router group. You should add all the routes that have common middlewares or the same path prefix. For example, all the routes that use a common middleware for authorization could be grouped.

func (*RouterGroup) HEAD

func (group *RouterGroup) HEAD(relativePath string, handlers ...HandlerFunc) IRoutes

HEAD is a shortcut for router.Handle("HEAD", path, handlers).

func (*RouterGroup) Handle

func (group *RouterGroup) Handle(httpMethod, relativePath string, handlers ...HandlerFunc) IRoutes

Handle registers a new request handle and middleware with the given path and method. The last handler should be the real handler, the other ones should be middleware that can and should be shared among different routes. See the example code in GitHub.

For GET, POST, PUT, PATCH and DELETE requests the respective shortcut functions can be used.

This function is intended for bulk loading and to allow the usage of less frequently used, non-standardized or custom methods (e.g. for internal communication with a proxy).

func (*RouterGroup) Match

func (group *RouterGroup) Match(methods []string, relativePath string, handlers ...HandlerFunc) IRoutes

Match registers a route that matches the specified methods that you declared.

func (*RouterGroup) OPTIONS

func (group *RouterGroup) OPTIONS(relativePath string, handlers ...HandlerFunc) IRoutes

OPTIONS is a shortcut for router.Handle("OPTIONS", path, handlers).

func (*RouterGroup) PATCH

func (group *RouterGroup) PATCH(relativePath string, handlers ...HandlerFunc) IRoutes

PATCH is a shortcut for router.Handle("PATCH", path, handlers).

func (*RouterGroup) POST

func (group *RouterGroup) POST(relativePath string, handlers ...HandlerFunc) IRoutes

POST is a shortcut for router.Handle("POST", path, handlers).

func (*RouterGroup) PUT

func (group *RouterGroup) PUT(relativePath string, handlers ...HandlerFunc) IRoutes

PUT is a shortcut for router.Handle("PUT", path, handlers).

func (*RouterGroup) Use

func (group *RouterGroup) Use(middleware ...HandlerFunc) IRoutes

Use adds middleware to the group, see example code in GitHub.

Directories

Path Synopsis
internal

Jump to

Keyboard shortcuts

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