Documentation ¶
Index ¶
- Constants
- Variables
- func BytesToString(b []byte) string
- func CopyBytes(b []byte) []byte
- func CopyString(s string) string
- func EqualFold(b, s string) (equals bool)
- func EqualFoldBytes(b, s []byte) (equals bool)
- func GetMIME(extension string) (mime string)
- func GetTrimmedParam(param string) string
- func Go(goroutine func())
- func GoWithRecover(goroutine func(), customRecover func(err interface{}))
- func LoadConfigFile(confFile string) map[string]interface{}
- func ReadFile(path string, fs http.FileSystem) ([]byte, error)
- func RegisterModule(inst Module)
- func SaveConfigFile(conf map[string]interface{}) error
- func StatusMessage(status int) string
- func StringToBytes(s string) (bs []byte)
- func ToHandle(src string) string
- func ToLower(b string) string
- func ToLowerBytes(b []byte) []byte
- func ToUpper(b string) string
- func ToUpperBytes(b []byte) []byte
- func Trim(s string, cutset byte) string
- func TrimBytes(b []byte, cutset byte) []byte
- func TrimLeft(s string, cutset byte) string
- func TrimLeftBytes(b []byte, cutset byte) []byte
- func TrimRight(s string, cutset byte) string
- func TrimRightBytes(b []byte, cutset byte) []byte
- func Walk(fs http.FileSystem, root string, walkFn filepath.WalkFunc) error
- type Array
- type Cookie
- type Core
- type Ctx
- func (c *Ctx) Append(field string, values ...string)
- func (c *Ctx) Body() []byte
- func (c *Ctx) ClearCookie(key ...string)
- func (c *Ctx) ClearCookies(key ...string)
- func (c *Ctx) ContentType(extension string, charset ...string) *Ctx
- func (c *Ctx) Cookie(cookie *Cookie)
- func (c *Ctx) Cookies(key string, defaultValue ...string) string
- func (c *Ctx) DelCookie(k string, path ...string)
- func (c *Ctx) FileBuf(fh *multipart.FileHeader) ([]byte, error)
- func (c *Ctx) FormFile(key string) (*multipart.FileHeader, error)
- func (c *Ctx) FormValue(key string, defaultValue ...string) string
- func (c *Ctx) Fresh() bool
- func (c *Ctx) Get(key string, defaultValue ...string) string
- func (c *Ctx) Hostname() string
- func (c *Ctx) IP() string
- func (c *Ctx) JSON(data interface{}) error
- func (c *Ctx) JSONP(data interface{}, callback ...string) error
- func (c *Ctx) MultipartForm() (*multipart.Form, error)
- func (c *Ctx) Next()
- func (c *Ctx) OriginalURL() string
- func (c *Ctx) Params(key string, defaultValue ...string) string
- func (c *Ctx) Path(override ...string) string
- func (c *Ctx) ReadBody(out interface{}) error
- func (c *Ctx) Render(f string, optionalBind ...interface{}) error
- func (c *Ctx) RenderString(src string, optionalBind ...interface{}) (string, error)
- func (c *Ctx) SaveFile(fileheader *multipart.FileHeader, path string) error
- func (c *Ctx) Send(body []byte) error
- func (c *Ctx) SendFile(file string, compress ...bool) error
- func (c *Ctx) SendStatus(status int) error
- func (c *Ctx) SendString(body string) error
- func (c *Ctx) Set(key string, val string)
- func (c *Ctx) Status(status int) *Ctx
- func (c *Ctx) ToJSON(data interface{}, err error) error
- func (c *Ctx) Vars(key string, value ...interface{}) (val interface{})
- func (c *Ctx) ViewTheme(theme string)
- func (c *Ctx) Write(p []byte) (int, error)
- func (c *Ctx) WriteString(s string) (int, error)
- type DB
- type Dict
- type Engine
- type Error
- type ErrorHandler
- type Hand
- type Handler
- func (h *Handler) Core(c ...*Core) *Core
- func (h *Handler) HandName() string
- func (h *Handler) Init()
- func (h *Handler) Prefix() string
- func (h *Handler) Preload(c *Ctx)
- func (h *Handler) PushPath(method, path string)
- func (h *Handler) SetHandName(name string)
- func (h *Handler) SetPrefix(prefix string)
- type Map
- type Model
- type Module
- type ModuleInfo
- type Options
- type Pages
- type Route
- type Static
- type StringOrNil
- type ViewEngine
- func (ve *ViewEngine) AddFunc(name string, fn interface{}) *ViewEngine
- func (ve *ViewEngine) Delims(l, r string) *ViewEngine
- func (ve *ViewEngine) DoTheme(theme string)
- func (ve *ViewEngine) Execute(out io.Writer, tpl string, binding interface{}, layout ...string) error
- func (ve *ViewEngine) ExecuteWriter(out io.Writer, tpl string, binding interface{}, layout ...string) error
- func (ve *ViewEngine) Layout(layout string) *ViewEngine
- func (ve *ViewEngine) Load() error
- func (ve *ViewEngine) Reload(reload bool) *ViewEngine
- func (ve *ViewEngine) Theme(theme string)
- type Views
Constants ¶
const ( MethodConnect = "CONNECT" // RFC 7231, 4.3.6 MethodDelete = "DELETE" // RFC 7231, 4.3.5 MethodGet = "GET" // RFC 7231, 4.3.1 MethodHead = "HEAD" // RFC 7231, 4.3.2 MethodOptions = "OPTIONS" // RFC 7231, 4.3.7 MethodPatch = "PATCH" // RFC 5789 MethodPost = "POST" // RFC 7231, 4.3.3 MethodPut = "PUT" // RFC 7231, 4.3.4 MethodTrace = "TRACE" // RFC 7231, 4.3.8 )
HTTP methods were copied from net/http.
const ( MIMETextXML = "text/xml" MIMETextHTML = "text/html" MIMETextPlain = "text/plain" MIMEApplicationXML = "application/xml" MIMEApplicationJSON = "application/json" MIMEApplicationJavaScript = "application/javascript" MIMEApplicationForm = "application/x-www-form-urlencoded" MIMEOctetStream = "application/octet-stream" MIMEMultipartForm = "multipart/form-data" MIMETextXMLCharsetUTF8 = "text/xml; charset=utf-8" MIMETextHTMLCharsetUTF8 = "text/html; charset=utf-8" MIMETextPlainCharsetUTF8 = "text/plain; charset=utf-8" MIMEApplicationXMLCharsetUTF8 = "application/xml; charset=utf-8" MIMEApplicationJSONCharsetUTF8 = "application/json; charset=utf-8" MIMEApplicationJavaScriptCharsetUTF8 = "application/javascript; charset=utf-8" )
MIME types that are commonly used
const ( StatusContinue = 100 // RFC 7231, 6.2.1 StatusSwitchingProtocols = 101 // RFC 7231, 6.2.2 StatusProcessing = 102 // RFC 2518, 10.1 StatusEarlyHints = 103 // RFC 8297 StatusOK = 200 // RFC 7231, 6.3.1 StatusCreated = 201 // RFC 7231, 6.3.2 StatusAccepted = 202 // RFC 7231, 6.3.3 StatusNonAuthoritativeInformation = 203 // RFC 7231, 6.3.4 StatusNoContent = 204 // RFC 7231, 6.3.5 StatusResetContent = 205 // RFC 7231, 6.3.6 StatusPartialContent = 206 // RFC 7233, 4.1 StatusMultiStatus = 207 // RFC 4918, 11.1 StatusAlreadyReported = 208 // RFC 5842, 7.1 StatusIMUsed = 226 // RFC 3229, 10.4.1 StatusMultipleChoices = 300 // RFC 7231, 6.4.1 StatusMovedPermanently = 301 // RFC 7231, 6.4.2 StatusFound = 302 // RFC 7231, 6.4.3 StatusSeeOther = 303 // RFC 7231, 6.4.4 StatusNotModified = 304 // RFC 7232, 4.1 StatusUseProxy = 305 // RFC 7231, 6.4.5 StatusTemporaryRedirect = 307 // RFC 7231, 6.4.7 StatusPermanentRedirect = 308 // RFC 7538, 3 StatusBadRequest = 400 // RFC 7231, 6.5.1 StatusPaymentRequired = 402 // RFC 7231, 6.5.2 StatusForbidden = 403 // RFC 7231, 6.5.3 StatusNotFound = 404 // RFC 7231, 6.5.4 StatusMethodNotAllowed = 405 // RFC 7231, 6.5.5 StatusNotAcceptable = 406 // RFC 7231, 6.5.6 StatusProxyAuthRequired = 407 // RFC 7235, 3.2 StatusRequestTimeout = 408 // RFC 7231, 6.5.7 StatusConflict = 409 // RFC 7231, 6.5.8 StatusGone = 410 // RFC 7231, 6.5.9 StatusLengthRequired = 411 // RFC 7231, 6.5.10 StatusPreconditionFailed = 412 // RFC 7232, 4.2 StatusRequestEntityTooLarge = 413 // RFC 7231, 6.5.11 StatusRequestURITooLong = 414 // RFC 7231, 6.5.12 StatusUnsupportedMediaType = 415 // RFC 7231, 6.5.13 StatusRequestedRangeNotSatisfiable = 416 // RFC 7233, 4.4 StatusExpectationFailed = 417 // RFC 7231, 6.5.14 StatusTeapot = 418 // RFC 7168, 2.3.3 StatusMisdirectedRequest = 421 // RFC 7540, 9.1.2 StatusUnprocessableEntity = 422 // RFC 4918, 11.2 StatusLocked = 423 // RFC 4918, 11.3 StatusFailedDependency = 424 // RFC 4918, 11.4 StatusTooEarly = 425 // RFC 8470, 5.2. StatusUpgradeRequired = 426 // RFC 7231, 6.5.15 StatusPreconditionRequired = 428 // RFC 6585, 3 StatusTooManyRequests = 429 // RFC 6585, 4 StatusRequestHeaderFieldsTooLarge = 431 // RFC 6585, 5 StatusInternalServerError = 500 // RFC 7231, 6.6.1 StatusNotImplemented = 501 // RFC 7231, 6.6.2 StatusBadGateway = 502 // RFC 7231, 6.6.3 StatusGatewayTimeout = 504 // RFC 7231, 6.6.5 StatusHTTPVersionNotSupported = 505 // RFC 7231, 6.6.6 StatusVariantAlsoNegotiates = 506 // RFC 2295, 8.1 StatusInsufficientStorage = 507 // RFC 4918, 11.5 StatusLoopDetected = 508 // RFC 5842, 7.2 StatusNotExtended = 510 // RFC 2774, 7 StatusNetworkAuthenticationRequired = 511 // RFC 6585, 6 )
HTTP status codes were copied from net/http.
const ( HeaderAuthorization = "Authorization" HeaderProxyAuthenticate = "Proxy-Authenticate" HeaderProxyAuthorization = "Proxy-Authorization" HeaderWWWAuthenticate = "WWW-Authenticate" HeaderAge = "Age" HeaderCacheControl = "Cache-Control" HeaderClearSiteData = "Clear-Site-Data" HeaderExpires = "Expires" HeaderPragma = "Pragma" HeaderWarning = "Warning" HeaderAcceptCH = "Accept-CH" HeaderAcceptCHLifetime = "Accept-CH-Lifetime" HeaderContentDPR = "Content-DPR" HeaderDPR = "DPR" HeaderEarlyData = "Early-Data" HeaderSaveData = "Save-Data" HeaderViewportWidth = "Viewport-Width" HeaderWidth = "Width" HeaderETag = "ETag" HeaderIfMatch = "If-Match" HeaderIfModifiedSince = "If-Modified-Since" HeaderIfNoneMatch = "If-None-Match" HeaderIfUnmodifiedSince = "If-Unmodified-Since" HeaderLastModified = "Last-Modified" HeaderVary = "Vary" HeaderConnection = "Connection" HeaderKeepAlive = "Keep-Alive" HeaderAccept = "Accept" HeaderAcceptCharset = "Accept-Charset" HeaderAcceptEncoding = "Accept-Encoding" HeaderAcceptLanguage = "Accept-Language" HeaderCookie = "Cookie" HeaderExpect = "Expect" HeaderMaxForwards = "Max-Forwards" HeaderSetCookie = "Set-Cookie" HeaderAccessControlAllowCredentials = "Access-Control-Allow-Credentials" HeaderAccessControlAllowHeaders = "Access-Control-Allow-Headers" HeaderAccessControlAllowMethods = "Access-Control-Allow-Methods" HeaderAccessControlAllowOrigin = "Access-Control-Allow-Origin" HeaderAccessControlExposeHeaders = "Access-Control-Expose-Headers" HeaderAccessControlMaxAge = "Access-Control-Max-Age" HeaderAccessControlRequestHeaders = "Access-Control-Request-Headers" HeaderAccessControlRequestMethod = "Access-Control-Request-Method" HeaderOrigin = "Origin" HeaderTimingAllowOrigin = "Timing-Allow-Origin" HeaderXPermittedCrossDomainPolicies = "X-Permitted-Cross-Domain-Policies" HeaderDNT = "DNT" HeaderTk = "Tk" HeaderContentDisposition = "Content-Disposition" HeaderContentEncoding = "Content-Encoding" HeaderContentLanguage = "Content-Language" HeaderContentLength = "Content-Length" HeaderContentLocation = "Content-Location" HeaderContentType = "Content-Type" HeaderForwarded = "Forwarded" HeaderVia = "Via" HeaderXForwardedFor = "X-Forwarded-For" HeaderXForwardedHost = "X-Forwarded-Host" HeaderXForwardedProto = "X-Forwarded-Proto" HeaderXForwardedProtocol = "X-Forwarded-Protocol" HeaderXForwardedSsl = "X-Forwarded-Ssl" HeaderXUrlScheme = "X-Url-Scheme" HeaderLocation = "Location" HeaderFrom = "From" HeaderHost = "Host" HeaderReferer = "Referer" HeaderReferrerPolicy = "Referrer-Policy" HeaderUserAgent = "User-Agent" HeaderAllow = "Allow" HeaderServer = "Server" HeaderAcceptRanges = "Accept-Ranges" HeaderContentRange = "Content-Range" HeaderIfRange = "If-Range" HeaderRange = "Range" HeaderContentSecurityPolicy = "Content-Security-Policy" HeaderContentSecurityPolicyReportOnly = "Content-Security-Policy-Report-Only" HeaderCrossOriginResourcePolicy = "Cross-Origin-Resource-Policy" HeaderExpectCT = "Expect-CT" HeaderFeaturePolicy = "Feature-Policy" HeaderPublicKeyPins = "Public-Key-Pins" HeaderPublicKeyPinsReportOnly = "Public-Key-Pins-Report-Only" HeaderStrictTransportSecurity = "Strict-Transport-Security" HeaderUpgradeInsecureRequests = "Upgrade-Insecure-Requests" HeaderXContentTypeOptions = "X-Content-Type-Options" HeaderXDownloadOptions = "X-Download-Options" HeaderXFrameOptions = "X-Frame-Options" HeaderXPoweredBy = "X-Powered-By" HeaderXXSSProtection = "X-XSS-Protection" HeaderLastEventID = "Last-Event-ID" HeaderNEL = "NEL" HeaderPingFrom = "Ping-From" HeaderPingTo = "Ping-To" HeaderReportTo = "Report-To" HeaderTE = "TE" HeaderTrailer = "Trailer" HeaderTransferEncoding = "Transfer-Encoding" HeaderSecWebSocketAccept = "Sec-WebSocket-Accept" HeaderSecWebSocketExtensions = "Sec-WebSocket-Extensions" HeaderSecWebSocketKey = "Sec-WebSocket-Key" HeaderSecWebSocketProtocol = "Sec-WebSocket-Protocol" HeaderSecWebSocketVersion = "Sec-WebSocket-Version" HeaderAcceptPatch = "Accept-Patch" HeaderAcceptPushPolicy = "Accept-Push-Policy" HeaderAcceptSignature = "Accept-Signature" HeaderAltSvc = "Alt-Svc" HeaderDate = "Date" HeaderIndex = "Index" HeaderLargeAllocation = "Large-Allocation" HeaderLink = "Link" HeaderPushPolicy = "Push-Policy" HeaderRetryAfter = "Retry-After" HeaderServerTiming = "Server-Timing" HeaderSignature = "Signature" HeaderSignedHeaders = "Signed-Headers" HeaderSourceMap = "SourceMap" HeaderUpgrade = "Upgrade" HeaderXDNSPrefetchControl = "X-DNS-Prefetch-Control" HeaderXPingback = "X-Pingback" HeaderXRequestID = "X-Request-ID" HeaderXRequestedWith = "X-Requested-With" HeaderXRobotsTag = "X-Robots-Tag" HeaderXUACompatible = "X-UA-Compatible" )
HTTP Headers were copied from net/http.
const ( DefaultDateFormat = "2006-01-02" DefaultDateTimeFormat = "2006-01-02 15:04" )
Revel's default date and time constants
Variables ¶
var ( ErrBadRequest = NewError(StatusBadRequest) // RFC 7231, 6.5.1 ErrPaymentRequired = NewError(StatusPaymentRequired) // RFC 7231, 6.5.2 ErrForbidden = NewError(StatusForbidden) // RFC 7231, 6.5.3 ErrNotFound = NewError(StatusNotFound) // RFC 7231, 6.5.4 ErrMethodNotAllowed = NewError(StatusMethodNotAllowed) // RFC 7231, 6.5.5 ErrNotAcceptable = NewError(StatusNotAcceptable) // RFC 7231, 6.5.6 ErrProxyAuthRequired = NewError(StatusProxyAuthRequired) // RFC 7235, 3.2 ErrRequestTimeout = NewError(StatusRequestTimeout) // RFC 7231, 6.5.7 ErrConflict = NewError(StatusConflict) // RFC 7231, 6.5.8 ErrGone = NewError(StatusGone) // RFC 7231, 6.5.9 ErrLengthRequired = NewError(StatusLengthRequired) // RFC 7231, 6.5.10 ErrPreconditionFailed = NewError(StatusPreconditionFailed) // RFC 7232, 4.2 ErrRequestEntityTooLarge = NewError(StatusRequestEntityTooLarge) // RFC 7231, 6.5.11 ErrRequestURITooLong = NewError(StatusRequestURITooLong) // RFC 7231, 6.5.12 ErrUnsupportedMediaType = NewError(StatusUnsupportedMediaType) // RFC 7231, 6.5.13 ErrRequestedRangeNotSatisfiable = NewError(StatusRequestedRangeNotSatisfiable) // RFC 7233, 4.4 ErrExpectationFailed = NewError(StatusExpectationFailed) // RFC 7231, 6.5.14 ErrTeapot = NewError(StatusTeapot) // RFC 7168, 2.3.3 ErrMisdirectedRequest = NewError(StatusMisdirectedRequest) // RFC 7540, 9.1.2 ErrUnprocessableEntity = NewError(StatusUnprocessableEntity) // RFC 4918, 11.2 ErrLocked = NewError(StatusLocked) // RFC 4918, 11.3 ErrFailedDependency = NewError(StatusFailedDependency) // RFC 4918, 11.4 ErrTooEarly = NewError(StatusTooEarly) // RFC 8470, 5.2. ErrUpgradeRequired = NewError(StatusUpgradeRequired) // RFC 7231, 6.5.15 ErrPreconditionRequired = NewError(StatusPreconditionRequired) // RFC 6585, 3 ErrTooManyRequests = NewError(StatusTooManyRequests) // RFC 6585, 4 ErrRequestHeaderFieldsTooLarge = NewError(StatusRequestHeaderFieldsTooLarge) // RFC 6585, 5 ErrInternalServerError = NewError(StatusInternalServerError) // RFC 7231, 6.6.1 ErrNotImplemented = NewError(StatusNotImplemented) // RFC 7231, 6.6.2 ErrBadGateway = NewError(StatusBadGateway) // RFC 7231, 6.6.3 ErrGatewayTimeout = NewError(StatusGatewayTimeout) // RFC 7231, 6.6.5 ErrHTTPVersionNotSupported = NewError(StatusHTTPVersionNotSupported) // RFC 7231, 6.6.6 ErrVariantAlsoNegotiates = NewError(StatusVariantAlsoNegotiates) // RFC 2295, 8.1 ErrInsufficientStorage = NewError(StatusInsufficientStorage) // RFC 4918, 11.5 ErrLoopDetected = NewError(StatusLoopDetected) // RFC 5842, 7.2 ErrNotExtended = NewError(StatusNotExtended) // RFC 2774, 7 ErrNetworkAuthenticationRequired = NewError(StatusNetworkAuthenticationRequired) // RFC 6585, 6 )
Errors
var ( // Log default global log interface Log log.Interface )
var Methods = []string{ MethodGet, MethodHead, MethodPost, MethodPut, MethodDelete, MethodConnect, MethodOptions, MethodTrace, MethodPatch, methodUse, }
Methods methods slice
Functions ¶
func BytesToString ¶
BytesToString returns a string pointer without allocation
func EqualFoldBytes ¶
EqualFoldBytes the equivalent of bytes.EqualFold
func GetTrimmedParam ¶
GetTrimmedParam trims the ':' & '?' from a string
func GoWithRecover ¶
func GoWithRecover(goroutine func(), customRecover func(err interface{}))
GoWithRecover starts a recoverable goroutine using given customRecover() function.
func LoadConfigFile ¶
LoadConfigFile load yml config
func ReadFile ¶
func ReadFile(path string, fs http.FileSystem) ([]byte, error)
ReadFile returns the raw content of a file
func SaveConfigFile ¶
func StatusMessage ¶
StatusMessage returns the correct message for the provided HTTP statuscode
func StringToBytes ¶
StringToBytes returns a byte pointer without allocation
func ToLowerBytes ¶
ToLowerBytes is the equivalent of bytes.ToLower
func ToUpperBytes ¶
ToUpperBytes is the equivalent of bytes.ToUpper
func TrimLeftBytes ¶
TrimLeftBytes is the equivalent of bytes.TrimLeft
func TrimRightBytes ¶
TrimRightBytes is the equivalent of bytes.TrimRight
Types ¶
type Cookie ¶
type Cookie struct { Name string `json:"name"` Value string `json:"value"` Path string `json:"path"` Domain string `json:"domain"` MaxAge int `json:"max_age"` Expires time.Time `json:"expires"` Secure bool `json:"secure"` HTTPOnly bool `json:"http_only"` SameSite string `json:"same_site"` }
Cookie data for c.Cookie
type Core ¶
Core cola core
type Ctx ¶
type Ctx struct { *Core // reference to *Core *fasthttp.RequestCtx // contains filtered or unexported fields }
Ctx Extends fasthttp RequestCtx
func (*Ctx) Append ¶
Append the specified value to the HTTP response header field. If the header is not already set, it creates the header with the specified value.
func (*Ctx) Body ¶
Body contains the raw body submitted in a POST request. Returned value is only valid within the handler. Do not store any references. Make copies or use the Immutable setting instead.
func (*Ctx) ClearCookie ¶
ClearCookie expires a specific cookie by key on the client side. If no key is provided it expires all cookies that came with the request.
func (*Ctx) ClearCookies ¶
ClearCookies clear cookie set default path /
if ClearCookie failed.
If no key is provided it expires all cookies that came with the request.
func (*Ctx) ContentType ¶
ContentType sets the Content-Type HTTP header(map[string] helper line 525 ) to the MIME type specified by the file extension.
func (*Ctx) Cookies ¶
Cookies is used for getting a cookie value by key. Defaults to the empty string "" if the cookie doesn't exist. If a default value is given, it will return that value if the cookie doesn't exist. The returned value is only valid within the handler. Do not store any references. Make copies or use the Immutable setting to use the value outside the Handler.
func (*Ctx) FileBuf ¶
func (c *Ctx) FileBuf(fh *multipart.FileHeader) ([]byte, error)
FileBuf Read request file
func (*Ctx) FormFile ¶
func (c *Ctx) FormFile(key string) (*multipart.FileHeader, error)
FormFile returns the first file by key from a MultipartForm.
func (*Ctx) FormValue ¶
FormValue returns the first value by key from a MultipartForm. Defaults to the empty string "" if the form value doesn't exist. If a default value is given, it will return that value if the form value does not exist. Returned value is only valid within the handler. Do not store any references. Make copies or use the Immutable setting instead.
func (*Ctx) Fresh ¶
Fresh returns true when the response is still “fresh” in the client's cache, otherwise false is returned to indicate that the client cache is now stale and the full response should be sent. When a client sends the Cache-Control: no-cache request header to indicate an end-to-end reload request, this module will return false to make handling these requests transparent. https://github.com/jshttp/fresh/blob/10e0471669dbbfbfd8de65bc6efac2ddd0bfa057/index.js#L33
func (*Ctx) Get ¶
Get returns the HTTP request header specified by field. Field names are case-insensitive Returned value is only valid within the handler. Do not store any references. Make copies or use the Immutable setting instead.
func (*Ctx) Hostname ¶
Hostname contains the hostname derived from the Host HTTP header. Returned value is only valid within the handler. Do not store any references. Make copies or use the Immutable setting instead.
func (*Ctx) JSON ¶
JSON converts any interface or string to JSON. Array and slice values encode as JSON arrays, except that []byte encodes as a base64-encoded string, and a nil slice encodes as the null JSON value. This method also sets the content header to application/json.
func (*Ctx) JSONP ¶
JSONP sends a JSON response with JSONP support. This method is identical to JSON, except that it opts-in to JSONP callback support. By default, the callback name is simply callback.
func (*Ctx) MultipartForm ¶
MultipartForm parse form entries from binary. This returns a map[string][]string, so given a key the value will be a string slice.
func (*Ctx) OriginalURL ¶
OriginalURL contains the original request URL. Returned value is only valid within the handler. Do not store any references.
func (*Ctx) Params ¶
Params is used to get the route parameters. Defaults to empty string "" if the param doesn't exist. If a default value is given, it will return that value if the param doesn't exist. Returned value is only valid within the handler. Do not store any references. Make copies or use the Immutable setting to use the value outside the Handler.
func (*Ctx) Path ¶
Path returns the path part of the request URL. Optionally, you could override the path.
func (*Ctx) ReadBody ¶
ReadBody binds the request body to a struct. It supports decoding the following content types based on the Content-Type header: application/json, application/xml, application/x-www-form-urlencoded, multipart/form-data If none of the content types above are matched, it will return a ErrUnprocessableEntity error
func (*Ctx) RenderString ¶
RenderString Parse template string to string
e.g:
```go c.RenderString(`<div>Your price: {{ .price }}</div>`, map[string]interface{}{ "price": 12.5, }) // or use vars c.Vars("price", 12.5) c.RenderString(`<div>Your price: {{ .price }}</div>`) ```
func (*Ctx) SaveFile ¶
func (c *Ctx) SaveFile(fileheader *multipart.FileHeader, path string) error
SaveFile saves any multipart file to disk.
func (*Ctx) Send ¶
Send sets the HTTP response body without copying it. From this point onward the body argument must not be changed.
func (*Ctx) SendFile ¶
SendFile transfers the file from the given path. The file is not compressed by default, enable this by passing a 'true' argument Sets the Content-Type response HTTP header field based on the filenames extension.
func (*Ctx) SendStatus ¶
SendStatus sets the HTTP status code and if the response body is empty, it sets the correct status message in the body.
func (*Ctx) SendString ¶
SendString sets the HTTP response body for string types. This means no type assertion, recommended for faster performance
type Error ¶
Error represents an error that occurred while handling a request.
type ErrorHandler ¶
ErrorHandler defines a function that will process all errors returned from any handlers in the stack
type Handler ¶
type Handler struct { Handlers map[string]struct{} // contains filtered or unexported fields }
Handler Sample Handler
type Model ¶
type Model struct { ID uid.UID `gorm:"primaryKey"` CreatedAt time.Time UpdatedAt time.Time DeletedAt *gorm.DeletedAt `json:",omitempty"` }
func (*Model) BeforeCreate ¶
type ModuleInfo ¶
ModuleInfo ModuleInfo
type Options ¶
type Options struct { Prefork bool LogPath string Config interface{} UseCheck bool Layout string // Debug Default false Debug bool Views Views // Case sensitive routing, all to lowercase CaseSensitive bool // Nginx Caddy some proxy header X-Real-IP X-Forwarded-For // Default: "" ProxyHeader string // Server: cola ServerName string // Default: false ETag bool `json:"etag"` // Max body size that the server accepts. // -1 will decline any body size // // Default: 4 * 1024 * 1024 BodyLimit int `json:"body_limit"` // Maximum number of concurrent connections. // // Default: 256 * 1024 Concurrency int `json:"concurrency"` // When set to true, converts all encoded characters in the route back // before setting the path for the context, so that the routing, // the returning of the current url from the context `ctx.Path()` // and the paramters `ctx.Params(%key%)` with decoded characters will work // // Default: false UnescapePath bool `json:"unescape_path"` // The amount of time allowed to read the full request including body. // It is reset after the request handler has returned. // The connection's read deadline is reset when the connection opens. // // Default: unlimited ReadTimeout time.Duration `json:"read_timeout"` // The maximum duration before timing out writes of the response. // It is reset after the request handler has returned. // // Default: unlimited WriteTimeout time.Duration `json:"write_timeout"` // The maximum amount of time to wait for the next request when keep-alive is enabled. // If IdleTimeout is zero, the value of ReadTimeout is used. // // Default: unlimited IdleTimeout time.Duration `json:"idle_timeout"` // Per-connection buffer size for requests' reading. // This also limits the maximum header size. // Increase this buffer if your clients send multi-KB RequestURIs // and/or multi-KB headers (for example, BIG cookies). // // Default: 4096 ReadBufferSize int `json:"read_buffer_size"` // Per-connection buffer size for responses' writing. // // Default: 4096 WriteBufferSize int `json:"write_buffer_size"` // CompressedFileSuffix adds suffix to the original file name and // tries saving the resulting compressed file under the new file name. // // Default: ".gz" CompressedFileSuffix string `json:"compressed_file_suffix"` // contains filtered or unexported fields }
Options Global options
type Route ¶
type Route struct { Handlers []Hand Params []string Path string Method string // contains filtered or unexported fields }
Route route
type Static ¶
type Static struct { // When set to true, the server tries minimizing CPU usage by caching compressed files. // Optional. Default value false Compress bool `json:"compress"` // When set to true, enables byte range requests. // Optional. Default value false ByteRange bool `json:"byte_range"` // When set to true, enables directory browsing. // Optional. Default value false. Browse bool `json:"browse"` // The name of the index file for serving a directory. // Optional. Default value "index.html". Index string `json:"index"` // Expiration duration for inactive file handlers. // Use a negative time.Duration to disable it. // // Optional. Default value 10 * time.Second. CacheDuration time.Duration `json:"cache_duration"` // The value for the Cache-Control HTTP-header // that is set on the file response. MaxAge is defined in seconds. // // Optional. Default value 0. MaxAge int `json:"max_age"` }
Static defines configuration options when defining static assets.
type StringOrNil ¶
type StringOrNil string
空字符串 存入数据库 存 NULL ,这样会跳过数据库唯一索引的检查
func (*StringOrNil) Scan ¶
func (s *StringOrNil) Scan(src interface{}) error
implements sql.Scanner, will be invoked automatically when read from the db
func (StringOrNil) String ¶
func (s StringOrNil) String() string
type ViewEngine ¶
type ViewEngine struct { // templates Templates *template.Template // contains filtered or unexported fields }
ViewEngine html template engine
func NewView ¶
func NewView(directory, ext string, args ...interface{}) *ViewEngine
NewView Create view engine args:
string theme bool debug map[string]interface{} helper fn http.FileSystem file system
func (*ViewEngine) AddFunc ¶
func (ve *ViewEngine) AddFunc(name string, fn interface{}) *ViewEngine
AddFunc add helper func
func (*ViewEngine) Delims ¶
func (ve *ViewEngine) Delims(l, r string) *ViewEngine
Delims sets the action delimiters to the specified strings Default: {{ var }}
func (*ViewEngine) ExecuteWriter ¶
func (ve *ViewEngine) ExecuteWriter(out io.Writer, tpl string, binding interface{}, layout ...string) error
ExecuteWriter execute render
func (*ViewEngine) Layout ¶
func (ve *ViewEngine) Layout(layout string) *ViewEngine
Layout set layout file Layout
func (*ViewEngine) Reload ¶
func (ve *ViewEngine) Reload(reload bool) *ViewEngine
Reload if set to true the templates are reloading on each render, use it when you're in development and you don't want to restart