web

package module
v0.2.1 Latest Latest
Warning

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

Go to latest
Published: Jan 4, 2021 License: MIT Imports: 30 Imported by: 0

README

Web framework

  • golang workframe
  • support router
  • auto register router
  • micro serve
  • easy run
  • support go module go.mod

more doc

https://godoc.org/github.com/xs23933/web

examples


package main

import (
	"github.com/xs23933/web"
)

// handler.go
type Handler struct {
    web.Handler
}

// Init Init
func (h *Handler) Init() {
	h.SetPrefix("/api") // Add prefix
}

// Get get method
// get /api/
func (Handler) Get(c *web.Ctx) {
    c.Send("Hello world")
}

// GetParams Get something params
//  get /api/:param?
func (Handler) GetParams(c *web.Ctx) {
    c.Send("Param: ", c.Params("param"))
}

// PostParam PostParam
func (Handler) PostParam(c *web.Ctx) {
    form := make(map[string]interface{}, 0)  // or some struct
    c.ReadBody(&form)
	c.Send("Param ", c.Params("param"))
}

// PutParams 可选参数
// put /:param?
func (Handler) PutParams(c *web.Ctx) {
    form := make(map[string]interface{}, 0)  // or some struct
    c.ReadBody(&form)
	c.Send("Param? ", c.Params("param"))
}

// main.go
func main(){
    app := web.New(&web.Options{Debug: true})

    app.Use(new(Handler))
    // Serve(port) 
    if err := app.Serve(80); err != nil {
        panic(err)
    }
}


go run example/main.go

+ ---- Auto register router ---- +
| GET	/api/
| GET	/api/:param?
| POST	/api/:param
| PUT	/api/:param?
+ ------------------------------ +
Started server on 0.0.0.0:80

Documentation

Index

Constants

View Source
const (
	MethodGet     = "GET"     // RFC 7231, 4.3.1
	MethodHead    = "HEAD"    // RFC 7231, 4.3.2
	MethodPost    = "POST"    // RFC 7231, 4.3.3
	MethodPut     = "PUT"     // RFC 7231, 4.3.4
	MethodPatch   = "PATCH"   // RFC 5789
	MethodDelete  = "DELETE"  // RFC 7231, 4.3.5
	MethodConnect = "CONNECT" // RFC 7231, 4.3.6
	MethodOptions = "OPTIONS" // RFC 7231, 4.3.7
	MethodTrace   = "TRACE"   // RFC 7231, 4.3.8
)

HTTP methods were copied from net/http.

View Source
const (
	MIMETextXML   = "text/xml"
	MIMETextHTML  = "text/html"
	MIMETextPlain = "text/plain"

	MIMEApplicationJSON       = "application/json"
	MIMEApplicationJavaScript = "application/javascript"
	MIMEApplicationXML        = "application/xml"
	MIMEApplicationForm       = "application/x-www-form-urlencoded"

	MIMEMultipartForm = "multipart/form-data"

	MIMEOctetStream = "application/octet-stream"
)

MIME types were copied from labstack/echo

View Source
const (
	// Authentication
	HeaderAuthorization      = "Authorization"
	HeaderProxyAuthenticate  = "Proxy-Authenticate"
	HeaderProxyAuthorization = "Proxy-Authorization"
	HeaderWWWAuthenticate    = "WWW-Authenticate"

	// Caching
	HeaderAge           = "Age"
	HeaderCacheControl  = "Cache-Control"
	HeaderClearSiteData = "Clear-Site-Data"
	HeaderExpires       = "Expires"
	HeaderPragma        = "Pragma"
	HeaderWarning       = "Warning"

	// Client hints
	HeaderAcceptCH         = "Accept-CH"
	HeaderAcceptCHLifetime = "Accept-CH-Lifetime"
	HeaderContentDPR       = "Content-DPR"
	HeaderDPR              = "DPR"
	HeaderEarlyData        = "Early-Data"
	HeaderSaveData         = "Save-Data"
	HeaderViewportWidth    = "Viewport-Width"
	HeaderWidth            = "Width"

	// Conditionals
	HeaderETag              = "ETag"
	HeaderIfMatch           = "If-Match"
	HeaderIfModifiedSince   = "If-Modified-Since"
	HeaderIfNoneMatch       = "If-None-Match"
	HeaderIfUnmodifiedSince = "If-Unmodified-Since"
	HeaderLastModified      = "Last-Modified"
	HeaderVary              = "Vary"

	// Connection management
	HeaderConnection = "Connection"
	HeaderKeepAlive  = "Keep-Alive"

	// Content negotiation
	HeaderAccept         = "Accept"
	HeaderAcceptCharset  = "Accept-Charset"
	HeaderAcceptEncoding = "Accept-Encoding"
	HeaderAcceptLanguage = "Accept-Language"

	// Controls
	HeaderCookie      = "Cookie"
	HeaderExpect      = "Expect"
	HeaderMaxForwards = "Max-Forwards"
	HeaderSetCookie   = "Set-Cookie"

	// CORS
	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"

	// Do Not Track
	HeaderDNT = "DNT"
	HeaderTk  = "Tk"

	// Downloads
	HeaderContentDisposition = "Content-Disposition"

	// Message body information
	HeaderContentEncoding = "Content-Encoding"
	HeaderContentLanguage = "Content-Language"
	HeaderContentLength   = "Content-Length"
	HeaderContentLocation = "Content-Location"
	HeaderContentType     = "Content-Type"

	// Proxies
	HeaderForwarded       = "Forwarded"
	HeaderVia             = "Via"
	HeaderXForwardedFor   = "X-Forwarded-For"
	HeaderXForwardedHost  = "X-Forwarded-Host"
	HeaderXForwardedProto = "X-Forwarded-Proto"

	// Redirects
	HeaderLocation = "Location"

	// Request context
	HeaderFrom           = "From"
	HeaderHost           = "Host"
	HeaderReferer        = "Referer"
	HeaderReferrerPolicy = "Referrer-Policy"
	HeaderUserAgent      = "User-Agent"

	// Response context
	HeaderAllow  = "Allow"
	HeaderServer = "Server"

	// Range requests
	HeaderAcceptRanges = "Accept-Ranges"
	HeaderContentRange = "Content-Range"
	HeaderIfRange      = "If-Range"
	HeaderRange        = "Range"

	// Security
	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"

	// Server-sent event
	HeaderLastEventID = "Last-Event-ID"
	HeaderNEL         = "NEL"
	HeaderPingFrom    = "Ping-From"
	HeaderPingTo      = "Ping-To"
	HeaderReportTo    = "Report-To"

	// Transfer coding
	HeaderTE               = "TE"
	HeaderTrailer          = "Trailer"
	HeaderTransferEncoding = "Transfer-Encoding"

	// WebSockets
	HeaderSecWebSocketAccept     = "Sec-WebSocket-Accept"
	HeaderSecWebSocketExtensions = "Sec-WebSocket-Extensions"
	HeaderSecWebSocketKey        = "Sec-WebSocket-Key"
	HeaderSecWebSocketProtocol   = "Sec-WebSocket-Protocol"
	HeaderSecWebSocketVersion    = "Sec-WebSocket-Version"

	// Other
	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.

View Source
const (
	TextBlack = iota + 30
	TextRed
	TextGreen
	TextYellow
	TextBlue
	TextMagenta
	TextCyan
	TextWhite
)

Variables

This section is empty.

Functions

func Black

func Black(msg string) string

func Blue

func Blue(msg string) string

func Cyan

func Cyan(msg string) string

func GetBytes added in v0.1.6

func GetBytes(s string) (bs []byte)

GetBytes returns a byte pointer without allocation

func GetString added in v0.1.6

func GetString(b []byte) string

GetString returns a string pointer without allocation

func Green

func Green(msg string) string

func ImmutableString added in v0.1.6

func ImmutableString(s string) string

ImmutableString returns a immutable string with allocation

func Magenta

func Magenta(msg string) string

func Red

func Red(msg string) string

func SetColor

func SetColor(msg string, conf, bg, text int) string

func White

func White(msg string) string

func Yellow

func Yellow(msg string) string

Types

type Cookie struct {
	Name     string
	Value    string
	Path     string
	Domain   string
	Expires  time.Time
	Secure   bool
	HTTPOnly bool
	SameSite string
}

Cookie struct

type Core

type Core struct {
	*Options
	*fasthttp.Server
	// contains filtered or unexported fields
}

Core core class

func New

func New(opts ...*Options) *Core

New new core

func (*Core) Build added in v0.0.4

func (c *Core) Build() error

Build Initialize

func (*Core) Get added in v0.1.9

func (c *Core) Get(args ...interface{}) *Core

Get registers a middleware route.

func (*Core) LoadTpls added in v0.1.3

func (c *Core) LoadTpls(tpls map[string]string) error

LoadTpls 载入数据库中的模版引擎.

func (*Core) RegView added in v0.0.4

func (c *Core) RegView(viewEngine ViewEngine)

RegView 注册模版引擎

func (*Core) Serve

func (c *Core) Serve(address interface{}, tlsopt ...*tls.Config) error

Serve 启动

func (*Core) Static added in v0.0.7

func (c *Core) Static(prefix, root string, config ...Static) *Core

Static registers a new route with path prefix to serve static files from the provided root directory.

func (*Core) Use

func (c *Core) Use(args ...interface{}) *Core

Use registers a middleware route.

func (*Core) View added in v0.0.4

func (c *Core) View(writer io.Writer, filename string, layout string, bind interface{}) error

View executes and writes the result of a template file to the writer.

First parameter is the writer to write the parsed template. Second parameter is the relative, to templates directory, template filename, including extension. Third parameter is the layout, can be empty string. Forth parameter is the bindable data to the template, can be nil.

Use context.View to render templates to the client instead. Returns an error on failure, otherwise nil.

type Ctx

type Ctx struct {
	*Core
	*fasthttp.RequestCtx
	*Route
	// contains filtered or unexported fields
}

Ctx web context

func (*Ctx) Body

func (c *Ctx) Body() string

Body contains the raw body submitted in a POST request. If a key is provided, it returns the form value 获得某个值用 c.FormValue

func (*Ctx) ClearCookie

func (c *Ctx) ClearCookie(key ...string)

ClearCookie expires a specific cookie by key. If no key is provided it expires all cookies.

func (*Ctx) Cookie

func (c *Ctx) Cookie(cookie *Cookie)

Cookie sets a cookie by passing a cookie struct

func (*Ctx) Cookies

func (c *Ctx) Cookies(key ...string) (value string)

Cookies is used for getting a cookie value by key

func (*Ctx) Domain added in v0.1.1

func (c *Ctx) Domain(bases []string) string

Domain 返回域名 如果包含基础域名就返回二级域名 反之返回完整域名.

func (*Ctx) Download

func (c *Ctx) Download(file string, name ...string)

Download transfers the file from path as an attachment. Typically, browsers will prompt the user for download. By default, the Content-Disposition header filename= parameter is the filepath (this typically appears in the browser dialog). Override this default with the filename parameter.

func (*Ctx) FormValue

func (c *Ctx) FormValue(k string) (v string)

FormValue 读取 form的值

func (*Ctx) Fresh

func (c *Ctx) Fresh() bool

Fresh When the response is still “fresh” in the client’s cache true is returned, 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

func (c *Ctx) Get(k string) string

Get the http request header specified by field

func (Ctx) Host

func (c Ctx) Host() string

Host contains the hostname derived from the Host HTTP header.

func (*Ctx) Hostname added in v0.1.1

func (c *Ctx) Hostname() string

Hostname host name

func (*Ctx) IP

func (c *Ctx) IP() string

IP returns the remote IP address of the request.

func (*Ctx) IPs

func (c *Ctx) IPs() []string

IPs returns an string slice of IP addresses specified in the X-Forwarded-For request header.

func (*Ctx) JSON

func (c *Ctx) JSON(data interface{}) error

JSON 发送 json 数据

func (*Ctx) JSONP

func (c *Ctx) JSONP(data interface{}, callback ...string) error

JSONP 发送jsonp 数据

func (*Ctx) Method added in v0.1.0

func (ctx *Ctx) Method(override ...string) string

Method contains a string corresponding to the HTTP method of the request: GET, POST, PUT and so on.

func (*Ctx) Next

func (c *Ctx) Next(err ...error)

Next 执行下一个操作

func (*Ctx) Params

func (c *Ctx) Params(k string) (v string)

Params is used to get the route parameters.

func (*Ctx) Path

func (c *Ctx) Path() string

Path 返回path

func (*Ctx) Query

func (c *Ctx) Query(k string) (value string)

Query returns the query string parameter in the url.

func (*Ctx) ReadBody

func (c *Ctx) ReadBody(out interface{}) error

ReadBody 读取body 数据

func (*Ctx) Redirect

func (c *Ctx) Redirect(path string, status ...int)

Redirect 页面跳转

func (*Ctx) Render added in v0.1.7

func (c *Ctx) Render(filename string, optionalViewModel ...interface{}) error

Render 直接渲染不渲染 layout

func (*Ctx) RootDomain added in v0.1.7

func (c *Ctx) RootDomain(offset ...int) string

RootDomain 获取主域名 默认2位

func (*Ctx) Router added in v0.1.6

func (c *Ctx) Router() *Route

Router returns the matched Route struct.

func (*Ctx) SaveFile

func (c *Ctx) SaveFile(fileheader *multipart.FileHeader, path string) error

SaveFile saves any multipart file to disk.

func (*Ctx) Send

func (c *Ctx) Send(bodies ...interface{})

Send sets the HTTP response body. The Send body can be of any type.

func (*Ctx) SendFile

func (c *Ctx) SendFile(file string, noCompression ...bool)

SendFile transfers the from the give path.

func (*Ctx) SendStatus

func (c *Ctx) SendStatus(code int)

SendStatus 发送 http code

func (*Ctx) Set

func (c *Ctx) Set(k, v string)

Set ctx set header

func (*Ctx) Subdomains added in v0.1.1

func (c *Ctx) Subdomains(offset ...int) string

Subdomains 子域名.

func (*Ctx) ToJSON added in v0.0.8

func (c *Ctx) ToJSON(data interface{}, err error) error

ToJSON 返回js数据处理错误

func (*Ctx) Vars

func (c *Ctx) Vars(k string, v ...interface{}) (val interface{})

Vars 本地数据

func (*Ctx) View added in v0.0.4

func (c *Ctx) View(filename string, optionalViewModel ...interface{}) error

View 显示模版

func (*Ctx) Write

func (c *Ctx) Write(bodies ...interface{})

Write appends any input to the HTTP body response.

type Error added in v0.1.6

type Error struct {
	Code    int    `json:"code"`
	Message string `json:"message"`
}

Error http Error.

func NewError added in v0.1.6

func NewError(code int, message ...string) *Error

NewError NewError.

func (*Error) Error added in v0.1.6

func (e *Error) Error() string

type HTMLEngine added in v0.1.7

type HTMLEngine struct {
	Templates *template.Template
	// contains filtered or unexported fields
}

HTMLEngine contains the html view engine structure.

func HTML added in v0.1.7

func HTML(fs interface{}, extension string) *HTMLEngine

HTML creates and returns a new html view engine. The html engine used like the "html/template" standard go package but with a lot of extra features. The given "extension" MUST begin with a dot.

Usage: HTML("./views", ".html") or HTML(iris.Dir("./views"), ".html") or HTML(AssetFile(), ".html") for embedded data.

func (*HTMLEngine) AddFunc added in v0.1.7

func (s *HTMLEngine) AddFunc(funcName string, funcBody interface{})

AddFunc adds the function to the template's function map. It is legal to overwrite elements of the default actions: - url func(routeName string, args ...string) string - urlpath func(routeName string, args ...string) string - render func(fullPartialName string) (template.HTML, error). - tr func(lang, key string, args ...interface{}) string

func (*HTMLEngine) AddLayoutFunc added in v0.1.7

func (s *HTMLEngine) AddLayoutFunc(funcName string, funcBody interface{}) *HTMLEngine

AddLayoutFunc adds the function to the template's layout-only function map. It is legal to overwrite elements of the default layout actions: - yield func() (template.HTML, error) - current func() (string, error) - partial func(partialName string) (template.HTML, error) - partial_r func(partialName string) (template.HTML, error) - render func(fullPartialName string) (template.HTML, error).

func (*HTMLEngine) Delims added in v0.1.7

func (s *HTMLEngine) Delims(left, right string) *HTMLEngine

Delims sets the action delimiters to the specified strings, to be used in templates. An empty delimiter stands for the corresponding default: {{ or }}.

func (*HTMLEngine) ExecuteWriter added in v0.1.7

func (s *HTMLEngine) ExecuteWriter(w io.Writer, name, layout string, bindingData interface{}) error

ExecuteWriter executes a template and writes its result to the w writer.

func (*HTMLEngine) Ext added in v0.1.7

func (s *HTMLEngine) Ext() string

Ext returns the file extension which this view engine is responsible to render.

func (*HTMLEngine) Funcs added in v0.1.7

func (s *HTMLEngine) Funcs(funcMap template.FuncMap) *HTMLEngine

Funcs adds the elements of the argument map to the template's function map. It is legal to overwrite elements of the map. The return value is the template, so calls can be chained.

func (*HTMLEngine) Layout added in v0.1.7

func (s *HTMLEngine) Layout(layoutFile string) *HTMLEngine

Layout sets the layout template file which inside should use the {{ yield }} func to yield the main template file and optionally {{partial/partial_r/render}} to render other template files like headers and footers

The 'tmplLayoutFile' is a relative path of the templates base directory, for the template file with its extension.

Example: HTML("./templates", ".html").Layout("layouts/mainLayout.html")

// mainLayout.html is inside: "./templates/layouts/".

Note: Layout can be changed for a specific call action with the option: "layout" on the iris' context.Render function.

func (*HTMLEngine) Load added in v0.1.7

func (s *HTMLEngine) Load() error

Load parses the templates to the engine. It's also responsible to add the necessary global functions.

Returns an error if something bad happens, caller is responsible to handle that.

func (*HTMLEngine) LoadTpls added in v0.1.7

func (s *HTMLEngine) LoadTpls(tpls map[string]string) error

func (*HTMLEngine) Option added in v0.1.7

func (s *HTMLEngine) Option(opt ...string) *HTMLEngine

Option sets options for the template. Options are described by strings, either a simple string or "key=value". There can be at most one equals sign in an option string. If the option string is unrecognized or otherwise invalid, Option panics.

Known options:

missingkey: Control the behavior during execution if a map is indexed with a key that is not present in the map.

"missingkey=default" or "missingkey=invalid"
	The default behavior: Do nothing and continue execution.
	If printed, the result of the index operation is the string
	"<no value>".
"missingkey=zero"
	The operation returns the zero value for the map type's element.
"missingkey=error"
	Execution stops immediately with an error.

func (*HTMLEngine) PageDir added in v0.1.7

func (s *HTMLEngine) PageDir(path string) *HTMLEngine

PageDir PageDir

func (*HTMLEngine) ParseTemplate added in v0.1.7

func (s *HTMLEngine) ParseTemplate(name string, contents []byte, funcs template.FuncMap) (err error)

ParseTemplate adds a custom template to the root template.

func (*HTMLEngine) Reload added in v0.1.7

func (s *HTMLEngine) Reload(developmentMode bool) *HTMLEngine

Reload if set to true the templates are reloading on each render, use it when you're in development and you're boring of restarting the whole app when you edit a template file.

Note that if `true` is passed then only one `View -> ExecuteWriter` will be render each time, no concurrent access across clients, use it only on development status. It's good to be used side by side with the https://github.com/kataras/rizla reloader for go source files.

func (*HTMLEngine) RootDir added in v0.1.7

func (s *HTMLEngine) RootDir(root string) *HTMLEngine

RootDir sets the directory to be used as a starting point to load templates from the provided file system.

func (*HTMLEngine) SetFuncs added in v0.1.7

func (s *HTMLEngine) SetFuncs(funcMap template.FuncMap) *HTMLEngine

SetFuncs overrides the template funcs with the given "funcMap".

type HandlebarsEngine added in v0.0.4

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

HandlebarsEngine 引擎

func Handlebars added in v0.0.4

func Handlebars(directory, ext string) *HandlebarsEngine

Handlebars genera and return new handlebars view engine

func (*HandlebarsEngine) AddFunc added in v0.0.4

func (s *HandlebarsEngine) AddFunc(funcName string, funcBody interface{})

AddFunc adds the function to the template's function map. It is legal to overwrite elements of the default actions: - url func(routeName string, args ...string) string - urlpath func(routeName string, args ...string) string - render func(fullPartialName string) (raymond.HTML, error).

func (*HandlebarsEngine) Binary added in v0.0.4

func (s *HandlebarsEngine) Binary(assetFn func(name string) ([]byte, error), namesFn func() []string) *HandlebarsEngine

Binary optionally, use it when template files are distributed inside the app executable (.go generated files).

The assetFn and namesFn can come from the go-bindata library.

func (*HandlebarsEngine) Debug added in v0.1.6

func (s *HandlebarsEngine) Debug(dev bool) *HandlebarsEngine

Debug use debug model

func (*HandlebarsEngine) ExecuteWriter added in v0.0.4

func (s *HandlebarsEngine) ExecuteWriter(w io.Writer, filename string, layout string, bind interface{}) error

ExecuteWriter executes a template and writes its result to he w writer

func (*HandlebarsEngine) Ext added in v0.0.4

func (s *HandlebarsEngine) Ext() string

Ext returns the file extension which this view engine is responsible to render.

func (*HandlebarsEngine) Layout added in v0.0.4

func (s *HandlebarsEngine) Layout(layoutFile string) *HandlebarsEngine

Layout sets the layout template file which should use the {{ yield }} func to yield the main template file and optionally {{partial/partial_r/render}} to render other template files like headers and footers.

func (*HandlebarsEngine) Load added in v0.0.4

func (s *HandlebarsEngine) Load() error

Load parses the templates to the engine. It is responsible to add the necessary global functions.

Returns an error if something bad happens, user is responsible to catch it.

func (*HandlebarsEngine) LoadTpls added in v0.1.3

func (s *HandlebarsEngine) LoadTpls(tpls map[string]string) error

LoadTpls 载入数据库中的模版数据 if exists ignore.

func (*HandlebarsEngine) RegisterRender added in v0.1.7

func (s *HandlebarsEngine) RegisterRender(funcName string)

RegisterRender register custom method

func (*HandlebarsEngine) Reload added in v0.0.4

func (s *HandlebarsEngine) Reload(devMode bool) *HandlebarsEngine

Reload if set to true the templates are reloading on each render, use it when you're in development and you're boring of restarting the whole app when you edit a template file.

Note that if `true` is passed then only one `View -> ExecuteWriter` will be render each time, no concurrent access across clients, use it only on development status. It's good to be used side by side with the https://github.com/kataras/rizla reloader for go source files.

type Handler

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

Handler 基础分类

func (*Handler) Init

func (h *Handler) Init()

Init 初始化操作

func (*Handler) Prefix

func (h *Handler) Prefix() string

Prefix 初始化操作

func (*Handler) Preload

func (h *Handler) Preload(c *Ctx)

Preload 预处理使用 必须配置 Next结尾

func (*Handler) SetPrefix

func (h *Handler) SetPrefix(prefix string)

SetPrefix 设置前缀

type Options

type Options struct {
	Prefork bool // multiple go processes listening on the some port
	// ETag 发送etag
	ETag       bool
	ServerName string
	// Fasthttp options
	Concurrency        int // default: 256 * 1024
	NoDefaultDate      bool
	DisableKeepalive   bool
	ReadTimeout        time.Duration
	WriteTimeout       time.Duration
	IdleTimeout        time.Duration
	MaxRequestBodySize int
	Debug              bool
	ViewEngine         ViewEngine
}

Options all options

type Route

type Route struct {
	Method string         // http method
	Path   string         // original path
	Params []string       // path params
	Regexp *regexp.Regexp // regexp matcher

	Handler  func(*Ctx) // ctx handler
	Handlers []Handler  `json:"-"` // Ctx handlers
	// contains filtered or unexported fields
}

Route 路由

type Static added in v0.0.7

type Static struct {
	Compress  bool
	ByteRange bool
	Browse    bool
	Index     string
}

Static struct

type ViewEngine added in v0.0.4

type ViewEngine interface {
	Load() error
	ExecuteWriter(io.Writer, string, string, interface{}) error
	LoadTpls(map[string]string) error
}

ViewEngine 视图接口

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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