rock

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Nov 28, 2019 License: MIT Imports: 26 Imported by: 1

Documentation

Index

Constants

View Source
const (
	// CONNECT HTTP method
	CONNECT = http.MethodConnect
	// DELETE HTTP method
	DELETE = http.MethodDelete
	// GET HTTP method
	GET = http.MethodGet
	// HEAD HTTP method
	HEAD = http.MethodHead
	// OPTIONS HTTP method
	OPTIONS = http.MethodOptions
	// PATCH HTTP method
	PATCH = http.MethodPatch
	// POST HTTP method
	POST = http.MethodPost
	// PUT HTTP method
	PUT = http.MethodPut
	// TRACE HTTP method
	TRACE = http.MethodTrace

	ApplicationJSON                  = "application/json"
	ApplicationJSONCharsetUTF8       = ApplicationJSON + "; " + CharsetUTF8
	ApplicationJavaScript            = "application/javascript"
	ApplicationJavaScriptCharsetUTF8 = ApplicationJavaScript + "; " + CharsetUTF8
	ApplicationXML                   = "application/xml"
	ApplicationXMLCharsetUTF8        = ApplicationXML + "; " + CharsetUTF8
	ApplicationForm                  = "application/x-www-form-urlencoded"
	ApplicationProtobuf              = "application/protobuf"
	ApplicationMsgpack               = "application/msgpack"
	TextHTML                         = "text/html"
	TextHTMLCharsetUTF8              = TextHTML + "; " + CharsetUTF8
	TextPlain                        = "text/plain"
	TextPlainCharsetUTF8             = TextPlain + "; " + CharsetUTF8
	MultipartForm                    = "multipart/form-data"
	OctetStream                      = "application/octet-stream"

	CharsetUTF8 = "charset=utf-8"

	AcceptedLanguage   = "Accept-Language"
	AcceptEncoding     = "Accept-Encoding"
	Authorization      = "Authorization"
	ContentDisposition = "Content-Disposition"
	ContentEncoding    = "Content-Encoding"
	ContentLength      = "Content-Length"
	ContentType        = "Content-Type"
	Location           = "Location"
	Upgrade            = "Upgrade"
	Vary               = "Vary"
	WWWAuthenticate    = "WWW-Authenticate"
	XForwardedFor      = "X-Forwarded-For"
	XRealIP            = "X-Real-Ip"
	Allow              = "Allow"
	Origin             = "Origin"

	Gzip = "gzip"
)

HTTP Constant Terms and Variables

Variables

View Source
var DebugPrintRouteFunc func(httpMethod, absolutePath, handlerName string, nuHandlers int)
View Source
var DefaultWriter io.Writer = os.Stdout
View Source
var NativeChainHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {

	c := GetContext(w)
	b := c.BaseContext()

	b.request = r

	if b.index+1 < len(b.handlers) {
		c.Next()
	}
})

Functions

func GetPool

func GetPool() *pool.BufferPool

func IsDebugging

func IsDebugging() bool

IsDebugging returns true if the framework is running in debug mode. Use SetMode(gin.ReleaseMode) to disable debug mode.

func Stack

func Stack() []byte

stack returns a nicely formated stack frame, skipping skip frames

Types

type App

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

func Default

func Default() *App

func New

func New() *App

func (*App) BuiltInFormDecoder

func (l *App) BuiltInFormDecoder() *form.Decoder

BuiltInFormDecoder returns the built in form decoder github.com/go-playground/form in order for custom type to be registered.

func (*App) GetHTMLRender

func (r *App) GetHTMLRender() HTMLRender

func (*App) HTMLRender

func (r *App) HTMLRender(render HTMLRender)

HtmlTemplate use html template middleware

func (*App) Mux

func (app *App) Mux() *chi.Mux

func (*App) NewRouter

func (app *App) NewRouter(path string) *Router

func (*App) RegisterContext

func (l *App) RegisterContext(fn ContextFunc)

RegisterContext registers a custom Context function for creation and resetting of a global object passed per http request

func (*App) RegisterCustomHandler

func (l *App) RegisterCustomHandler(customType interface{}, fn CustomHandlerFunc)

RegisterCustomHandler registers a custom handler that gets wrapped by HandlerFunc

func (*App) Run

func (app *App) Run(addr string)

Run server with specific address and port

func (*App) ServeHTTP

func (app *App) ServeHTTP(w http.ResponseWriter, req *http.Request)

type Context

type Context interface {
	Request() *http.Request
	Response() *Response
	GetQuery(name string) (string, bool)

	Param(name string) string
	QueryParams() url.Values
	ParseForm() error
	ParseMultipartForm(maxMemory int64) error
	Next()
	ClientIP() (clientIP string)
	AcceptedLanguages(lowercase bool) []string
	Stream(step func(w io.Writer) bool)
	JSON(int, interface{}) error
	JSONBytes(int, []byte) error
	JSONP(int, interface{}, string) error
	XML(int, interface{}) error
	XMLBytes(int, []byte) error
	Text(int, string) error
	TextBytes(int, []byte) error
	Attachment(r io.Reader, filename string) (err error)
	Inline(r io.Reader, filename string) (err error)
	// Decode(includeFormQueryParams bool, maxMemory int64, v interface{}) (err error)
	Decode(v interface{}, args ...interface{}) (err error)
	BaseContext() *Ctx
	RequestStart(w http.ResponseWriter, r *http.Request)
	String(int, string, ...interface{})

	// Custom
	SetHandlers([]HandlerFunc)
	Data() M
	SetData(M)
	Set(key string, value interface{})
	Get(key string) (interface{}, bool)

	Abort()
	AbortWithStatus(code int)
	AbortWithStatusJSON(code int, jsonObj interface{})
	Redirect(url string)

	// Render
	HTMLRender(HTMLRender)
	Render(code int, r Render)
	Status(code int)
	HTML(string, ...int)

	MustPostInt(key string, d int) int
	MustPostString(key string, d string) string

	MustParamInt(name string, d int) int

	MustQueryInt(name string, d int) int

	FormFile(name string) (*multipart.FileHeader, error)
	// contains filtered or unexported methods
}

Context is the context interface type

func GetContext

func GetContext(w http.ResponseWriter) Context

GetContext is a helper method for retrieving the Context object from the ResponseWriter when using native go hanlders. NOTE: this will panic if fed an http.ResponseWriter not provided by lars's chaining.

type ContextFunc

type ContextFunc func(l *App) Context

ContextFunc is the function to run when creating a new context

type Ctx

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

func NewContext

func NewContext(l *App) *Ctx

NewContext returns a new default lars Context object.

func (*Ctx) Abort

func (c *Ctx) Abort()

func (*Ctx) AbortWithStatus

func (c *Ctx) AbortWithStatus(code int)

AbortWithStatus calls `Abort()` and writes the headers with the specified status code. For example, a failed attempt to authenticate a request could use: context.AbortWithStatus(401).

func (*Ctx) AbortWithStatusJSON

func (c *Ctx) AbortWithStatusJSON(code int, jsonObj interface{})

AbortWithStatusJSON calls `Abort()` and then `JSON` internally. This method stops the chain, writes the status code and return a JSON body. It also sets the Content-Type as "application/json".

func (*Ctx) AcceptedLanguages

func (c *Ctx) AcceptedLanguages(lowercase bool) []string

AcceptedLanguages returns an array of accepted languages denoted by the Accept-Language header sent by the browser NOTE: some stupid browsers send in locales lowercase when all the rest send it properly

func (*Ctx) Attachment

func (c *Ctx) Attachment(r io.Reader, filename string) (err error)

Attachment is a helper method for returning an attachement file to be downloaded, if you with to open inline see function

func (*Ctx) BaseContext

func (c *Ctx) BaseContext() *Ctx

BaseContext returns the underlying context object App uses internally. used when overriding the context object

func (*Ctx) ClientIP

func (c *Ctx) ClientIP() (clientIP string)

ClientIP implements a best effort algorithm to return the real client IP, it parses X-Real-IP and X-Forwarded-For in order to work properly with reverse-proxies such us: nginx or haproxy.

func (*Ctx) Data

func (c *Ctx) Data() M

func (*Ctx) Decode

func (c *Ctx) Decode(v interface{}, args ...interface{}) (err error)

Decode takes the request and attempts to discover it's content type via the http headers and then decode the request body into the provided struct. Example if header was "application/json" would decode using json.NewDecoder(io.LimitReader(c.request.Body, maxMemory)).Decode(v).

func (*Ctx) FormFile

func (c *Ctx) FormFile(name string) (*multipart.FileHeader, error)

func (*Ctx) Get

func (c *Ctx) Get(key string) (value interface{}, exists bool)

func (*Ctx) GetQuery

func (c *Ctx) GetQuery(name string) (string, bool)

func (*Ctx) HTML

func (c *Ctx) HTML(name string, status ...int)

func (*Ctx) HTMLRender

func (c *Ctx) HTMLRender(render HTMLRender)

func (*Ctx) Inline

func (c *Ctx) Inline(r io.Reader, filename string) (err error)

Inline is a helper method for returning a file inline to be rendered/opened by the browser

func (*Ctx) JSON

func (c *Ctx) JSON(code int, i interface{}) (err error)

JSON marshals provided interface + returns JSON + status code

func (*Ctx) JSONBytes

func (c *Ctx) JSONBytes(code int, b []byte) (err error)

JSONBytes returns provided JSON response with status code

func (*Ctx) JSONP

func (c *Ctx) JSONP(code int, i interface{}, callback string) (err error)

JSONP sends a JSONP response with status code and uses `callback` to construct the JSONP payload.

func (*Ctx) MustParamInt

func (c *Ctx) MustParamInt(name string, d int) int

func (*Ctx) MustPostInt

func (c *Ctx) MustPostInt(key string, d int) int

func (*Ctx) MustPostString

func (c *Ctx) MustPostString(key, d string) string

func (*Ctx) MustQueryInt

func (c *Ctx) MustQueryInt(name string, d int) int

func (*Ctx) Next

func (c *Ctx) Next()

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

func (*Ctx) Param

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

Params returns the url param by name.

func (*Ctx) ParseForm

func (c *Ctx) ParseForm() error

ParseForm calls the underlying http.Request ParseForm but also adds the URL params to the request Form as if they were defined as query params i.e. ?id=13&ok=true but does not add the params to the http.Request.URL.RawQuery for SEO purposes

func (*Ctx) ParseMultipartForm

func (c *Ctx) ParseMultipartForm(maxMemory int64) error

ParseMultipartForm calls the underlying http.Request ParseMultipartForm but also adds the URL params to the request Form as if they were defined as query params i.e. ?id=13&ok=true but does not add the params to the http.Request.URL.RawQuery for SEO purposes

func (*Ctx) QueryParams

func (c *Ctx) QueryParams() url.Values

QueryParams returns the http.Request.URL.Query() values this function is not for convenience, but rather performance URL.Query() reparses the RawQuery every time it's called, but this function will cache the initial parsing so it doesn't have to reparse; which is useful if when accessing these Params from multiple middleware.

func (*Ctx) Redirect

func (c *Ctx) Redirect(url string)

func (*Ctx) Render

func (c *Ctx) Render(statusCode int, r Render)

Render writes the response headers and calls render.Render to render data.

func (*Ctx) Request

func (c *Ctx) Request() *http.Request

func (*Ctx) RequestStart

func (c *Ctx) RequestStart(w http.ResponseWriter, r *http.Request)

RequestStart resets the Context to it's default request state

func (*Ctx) Response

func (c *Ctx) Response() *Response

func (*Ctx) Set

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

func (*Ctx) SetData

func (c *Ctx) SetData(data M)

set all data

func (*Ctx) SetHandlers

func (c *Ctx) SetHandlers(handlers []HandlerFunc)

func (*Ctx) Status

func (ctx *Ctx) Status(status int)

func (*Ctx) Stream

func (c *Ctx) Stream(step func(w io.Writer) bool)

Stream provides HTTP Streaming

func (*Ctx) String

func (c *Ctx) String(status int, format string, val ...interface{})

String response with text/html; charset=UTF-8 Content type

func (*Ctx) Text

func (c *Ctx) Text(code int, s string) error

Text returns the provided string with status code

func (*Ctx) TextBytes

func (c *Ctx) TextBytes(code int, b []byte) (err error)

TextBytes returns the provided response with status code

func (*Ctx) XML

func (c *Ctx) XML(code int, i interface{}) error

XML marshals provided interface + returns XML + status code

func (*Ctx) XMLBytes

func (c *Ctx) XMLBytes(code int, b []byte) (err error)

XMLBytes returns provided XML response with status code

type CustomHandlerFunc

type CustomHandlerFunc func(Context, Handler)

CustomHandlerFunc wraped by HandlerFunc and called where you can type cast both Context and Handler and call Handler

type HTMLRender

type HTMLRender interface {
	GetViewDir() string
	SetViewDir(string)
	Instance(string, interface{}) Render
}

type Handler

type Handler interface{}

type internally.

func LastHandler

func LastHandler(c []Handler) Handler

Last returns the last handler in the chain. ie. the last handler is the main own.

type HandlerFunc

type HandlerFunc func(Context)

HandlerFunc is the internal handler type used for middleware and handlers

func Logger

func Logger() HandlerFunc

NewLogger returns a new Logger instance

type HandlersChain

type HandlersChain []HandlerFunc

HandlersChain is an array of HanderFunc handlers to run

type M

type M map[string]interface{}

type Render

type Render interface {
	Render(w http.ResponseWriter, statusCode int)
}

type Response

type Response struct {
	http.ResponseWriter
	// contains filtered or unexported fields
}

Response struct contains methods and to capture extra data about the http request and more efficiently reset underlying writer object... it does comply with the http.ResponseWriter interface

func (*Response) CloseNotify

func (r *Response) CloseNotify() <-chan bool

CloseNotify wraps response writer's CloseNotify function.

func (*Response) Committed

func (r *Response) Committed() bool

Committed returns whether the *Response header has already been written to and if has been committed to this return.

func (*Response) Flush

func (r *Response) Flush()

Flush wraps response writer's Flush function.

func (*Response) Header

func (r *Response) Header() http.Header

Header returns the header map that will be sent by WriteHeader. Changing the header after a call to WriteHeader (or Write) has no effect unless the modified headers were declared as trailers by setting the "Trailer" header before the call to WriteHeader (see example). To suppress implicit *Response headers, set their value to nil.

func (*Response) Hijack

func (r *Response) Hijack() (net.Conn, *bufio.ReadWriter, error)

Hijack wraps response writer's Hijack function.

func (*Response) SetWriter

func (r *Response) SetWriter(w http.ResponseWriter)

SetWriter sets the provided writer as the new *Response http.ResponseWriter

func (*Response) Size

func (r *Response) Size() int64

Size returns the number of bytes written in the *Response

func (*Response) Status

func (r *Response) Status() int

Status returns the *Response's current http status code.

func (*Response) Write

func (r *Response) Write(b []byte) (n int, err error)

Write writes the data to the connection as part of an HTTP reply. If WriteHeader has not yet been called, Write calls WriteHeader(http.StatusOK) before writing the data. If the Header does not contain a Content-Type line, Write adds a Content-Type set to the result of passing the initial 512 bytes of written data to DetectContentType.

func (*Response) WriteHeader

func (r *Response) WriteHeader(code int)

WriteHeader sends an HTTP *Response header with status code. If WriteHeader is not called explicitly, the first call to Write will trigger an implicit WriteHeader(http.StatusOK). Thus explicit calls to WriteHeader are mainly used to send error codes.

func (*Response) WriteHeaderNow

func (w *Response) WriteHeaderNow()

func (*Response) WriteString

func (r *Response) WriteString(s string) (n int, err error)

WriteString write string to ResponseWriter

func (*Response) Writer

func (r *Response) Writer() http.ResponseWriter

Writer return the *Response's http.ResponseWriter object. Usually only used when creating middleware.

func (*Response) Written

func (w *Response) Written() bool

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

	Before(func(ResponseWriter))
	GetBefores() int
}

ResponseWriter ...

type Router

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

func (*Router) DELETE

func (r *Router) DELETE(path string, handlers ...Handler)

DELETE handle DELETE method

func (*Router) GET

func (r *Router) GET(path string, handlers ...Handler)

GET handle GET method

func (*Router) Group

func (r *Router) Group(path string, handlers ...Handler) *Router

Group group route

func (*Router) HEAD

func (r *Router) HEAD(path string, handlers ...Handler)

HEAD handle HEAD method

func (*Router) HTTPHandlerFunc

func (r *Router) HTTPHandlerFunc(h http.HandlerFunc) HandlerFunc

HandlerFunc convert http.HandlerFunc to ace.HandlerFunc

func (*Router) Handle

func (r *Router) Handle(method, path string, handlers []Handler)

Handle handle with specific method

func (*Router) Mount

func (r *Router) Mount(prefix string, handler http.Handler)

func (*Router) OPTIONS

func (r *Router) OPTIONS(path string, handlers ...Handler)

OPTIONS handle OPTIONS method

func (*Router) PATCH

func (r *Router) PATCH(path string, handlers ...Handler)

PATCH handle PATCH method

func (*Router) POST

func (r *Router) POST(path string, handlers ...Handler)

POST handle POST method

func (*Router) PUT

func (r *Router) PUT(path string, handlers ...Handler)

PUT handle PUT method

func (*Router) RouteNotFound

func (r *Router) RouteNotFound(h HandlerFunc)

RouteNotFound call when route does not match

func (*Router) Static

func (r *Router) Static(path string, root http.FileSystem, handlers ...HandlerFunc)

Static server static file path is url path root is root directory

func (*Router) Use

func (r *Router) Use(middlewares ...Handler)

Use register middleware

Jump to

Keyboard shortcuts

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