bigo

package module
v0.0.0-...-185a503 Latest Latest
Warning

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

Go to latest
Published: Oct 18, 2017 License: Apache-2.0 Imports: 30 Imported by: 1

README

Bigo is a web framework base on martini and macaron for quick start web develop

Copy the config.json to your workdir and create main.go:

package main

import (
	"github.com/fym201/bigo"
)

func main() {
	m := bigo.Classic()
	m.Get("/", func() string {
		return "Hello world!"
	})
	m.Run()
}

Documentation

Overview

Package bigo is a high productive and modular design web framework in Go.

Index

Constants

View Source
const (
	Dev  = "development"
	Prod = "production"
	Test = "test"
)
View Source
const (
	HeaderAcceptEncoding  = "Accept-Encoding"
	HeaderContentEncoding = "Content-Encoding"
	HeaderContentLength   = "Content-Length"
	HeaderContentType     = "Content-Type"
	HeaderVary            = "Vary"
)
View Source
const (
	ContentType   = "Content-Type"
	ContentLength = "Content-Length"
	ContentBinary = "application/octet-stream"
	ContentJSON   = "application/json"
	ContentHTML   = "text/html"
	CONTENT_PLAIN = "text/plain"
	ContentXHTML  = "application/xhtml+xml"
	ContentXML    = "text/xml"
)

Variables

View Source
var (
	// Env is the environment that Bigo is executing in.
	Env = Dev

	// Path of work directory.
	Root string

	// Flash applies to current request.
	FlashNow bool
)
View Source
var ColorLog = true

Functions

func DefaultLoggerWriter

func DefaultLoggerWriter() io.Writer

默认的日志输出

func GetExt

func GetExt(s string) string

func NewFileLoggerWriter

func NewFileLoggerWriter(dir string, logInterval time.Duration) io.Writer

创建一个输出到文件的log输出对象,dir为日志目录,logInterval切换日志文件的间隔时间,默认24小时

func NewRouteMap

func NewRouteMap() *routeMap

NewRouteMap initializes and returns a new routeMap.

func ParseTplSet

func ParseTplSet(tplSet string) (tplName string, tplDir string)

func PrepareCharset

func PrepareCharset(charset string) string

func SetEnv

func SetEnv(e string)

func Version

func Version() string

Types

type BeforeFunc

type BeforeFunc func(ResponseWriter)

BeforeFunc is a function that is called before the ResponseWriter has been written to.

type BeforeHandler

type BeforeHandler func(rw http.ResponseWriter, req *http.Request) bool

BeforeHandler represents a handler executes at beginning of every request. Bigo stops future process when it returns true.

type Bigo

type Bigo struct {
	inject.Injector

	*Router
	// contains filtered or unexported fields
}

Bigo represents the top level web application. inject.Injector methods can be invoked to map services on a global level.

func Classic

func Classic() *Bigo

Classic creates a classic Bigo with some basic default middleware: mocaron.Logger, mocaron.Recovery and mocaron.Static.

func New

func New() *Bigo

New creates a bare bones Bigo instance. Use this method if you want to have full control over the middleware that is used.

func NewWithLogger

func NewWithLogger(logger *Logger) *Bigo

NewWithLogger creates a bare bones Bigo instance. Use this method if you want to have full control over the middleware that is used. You can specify logger output writer with this function.

func (*Bigo) Action

func (m *Bigo) Action(handler Handler)

Action sets the handler that will be called after all the middleware has been invoked. This is set to macaron.Router in a macaron.Classic().

func (*Bigo) Before

func (m *Bigo) Before(handler BeforeHandler)

func (*Bigo) Handlers

func (m *Bigo) Handlers(handlers ...Handler)

Handlers sets the entire middleware stack with the given Handlers. This will clear any current middleware handlers, and panics if any of the handlers is not a callable function

func (*Bigo) Run

func (m *Bigo) Run()

func (*Bigo) RunHttp

func (m *Bigo) RunHttp(addr string, timeOut ...time.Duration)

timeOut first arg is ReadTimeout, sencond arg is WriteTimeout,default is 30 Seconds

func (*Bigo) RunHttps

func (m *Bigo) RunHttps(addr string, cerFile string, keyFile string, timeOut ...time.Duration)

func (*Bigo) ServeHTTP

func (m *Bigo) ServeHTTP(rw http.ResponseWriter, req *http.Request)

ServeHTTP is the HTTP Entry point for a Bigo instance. Useful if you want to control your own HTTP server. Be aware that none of middleware will run without registering any router.

func (*Bigo) SetDefaultCookieSecret

func (m *Bigo) SetDefaultCookieSecret(secret string)

SetDefaultCookieSecret sets global default secure cookie secret.

func (*Bigo) SetURLPrefix

func (m *Bigo) SetURLPrefix(prefix string)

SetURLPrefix sets URL prefix of router layer, so that it support suburl.

func (*Bigo) Use

func (m *Bigo) Use(handler Handler)

Use adds a middleware Handler to the stack, and panics if the handler is not a callable func. Middleware Handlers are invoked in the order that they are added.

type ComboRouter

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

ComboRouter represents a combo router.

func (*ComboRouter) Delete

func (cr *ComboRouter) Delete(h ...Handler) *ComboRouter

func (*ComboRouter) Get

func (cr *ComboRouter) Get(h ...Handler) *ComboRouter

func (*ComboRouter) Head

func (cr *ComboRouter) Head(h ...Handler) *ComboRouter

func (*ComboRouter) Options

func (cr *ComboRouter) Options(h ...Handler) *ComboRouter

func (*ComboRouter) Patch

func (cr *ComboRouter) Patch(h ...Handler) *ComboRouter

func (*ComboRouter) Post

func (cr *ComboRouter) Post(h ...Handler) *ComboRouter

func (*ComboRouter) Put

func (cr *ComboRouter) Put(h ...Handler) *ComboRouter

type Config

type Config struct {
	AppName  string   `json:"AppName"`  //应用名称
	WorkDir  string   `json:"WorkDir"`  //工作目录,默认为运行目录
	LogDir   string   `json:"LogDir"`   //日志目录,默认为$WORKDIR/log
	LogLevel LogLevel `json:"LogLevel"` //日志等级,0.none 1.info 2.debug 3.error ,默认在DEV,TEST下为1,PROD下为3

	HttpAddr string `json:"HttpAddr"` //http监听地址,默认在0.0.0.0
	HttpPort int    `json:"HttpPort"` //http监听端口,默认为3000

	HttpsAddr     string `json:"HttpsAddr"`     //https监听地址,默认在0.0.0.0
	HttpsPort     int    `json:"HttpsPort"`     //https监听地址,默认为443
	HttpsCertFile string `json:"HttpsCertFile"` //https证书文件路径
	HttpsKeyFile  string `json:"HttpsKeyFile"`  //https证书key文件路径
	EnableHttps   bool   `json:"EnableHttps"`   //是否开启https服务,默认false
	ForceHttps    bool   `json:"ForceHttps"`    //是否强制将http请求转为https,默认为false

	EnableGzip bool `json:"EnableGzip"` //是否开启gzip,默认true,如果开启,并且客户端接受gzip的话责对会话进行gzip压缩
	ForceGzip  bool `json:"ForceGzip"`  //是否强制开启gzip,默认false,如果开启,不管客户端接不接受,都会以gzip进行传输

	EnableMinify           bool        `json:"EnableMinify"`           //默认为true,是否对.html .js .css 进行最小化处理
	StaticExtensionsToGzip []string    `json:"StaticExtensionsToGzip"` //使用gzip进行压缩传输的静态文件后缀,受客户端协议或FORCE_GZIP影响
	Statics                []StaticOpt `json:"Statics"`                //静态目录,数组
	I18n                   *I18nOpt    `json:"i18n"`                   //本地化配置
	Tmpl                   *TmplOpt    `json:"Tmpl"`                   //模板引擎配置
	RunMode                string      `json:"RunMode"`                //运行模式,DEV为开发模式,PROD为发布模式,TEST为测试模式
	DevOpt                 *SubConfig  `json:"DEV"`                    //对于DEV模式下的配置,RUN_MODE为DEV时会覆盖顶级配置
	TestOpt                *SubConfig  `json:"TEST"`                   //对于TEST模式下的配置,RUN_MODE为TEST时会覆盖顶级配置
	ProdOpt                *SubConfig  `json:"PROD"`                   //对于PROD模式下的配置,RUN_MODE为PROD时会覆盖顶级配置

	CutomOpt map[string]interface{} `json:"Cutom"` //自定义选项
}

如果以【app -c configPath】的命令行形式指定了文件,那么直接加载这个文件,否则 查找当前工作目录下的config.json 查找app所在目录下的config.json

func GetConfig

func GetConfig() *Config

func LoadConfig

func LoadConfig() (c *Config, err error)

加载系统配置

func (*Config) Custom

func (c *Config) Custom(key string) interface{}

func (*Config) CustomFloat32

func (c *Config) CustomFloat32(key string) float32

func (*Config) CustomFloat64

func (c *Config) CustomFloat64(key string) float64

func (*Config) CustomInt

func (c *Config) CustomInt(key string) int

func (*Config) CustomInt64

func (c *Config) CustomInt64(key string) int64

func (*Config) CustomString

func (c *Config) CustomString(key string) string

type Context

type Context struct {
	inject.Injector

	*Router
	Req  Request
	Resp ResponseWriter

	Render // Not nil only if you use macaran.Render middleware.
	ILocale
	Data map[string]interface{}
	// contains filtered or unexported fields
}

Context represents the runtime context of current request of Bigo instance. It is the integration of most frequently used middlewares and helper methods.

func (*Context) ChangeStaticPath

func (ctx *Context) ChangeStaticPath(oldPath, newPath string)

ChangeStaticPath changes static path from old to new one.

func (*Context) GetCookie

func (ctx *Context) GetCookie(name string) string

GetCookie returns given cookie value from request header.

func (*Context) GetCookieFloat64

func (ctx *Context) GetCookieFloat64(name string) float64

GetCookieFloat64 returns cookie result in float64 type.

func (*Context) GetCookieInt

func (ctx *Context) GetCookieInt(name string) int

GetCookieInt returns cookie result in int type.

func (*Context) GetCookieInt64

func (ctx *Context) GetCookieInt64(name string) int64

GetCookieInt64 returns cookie result in int64 type.

func (*Context) GetFile

func (ctx *Context) GetFile(name string) (multipart.File, *multipart.FileHeader, error)

GetFile returns information about user upload file by given form field name.

func (*Context) GetSecureCookie

func (ctx *Context) GetSecureCookie(key string) (string, bool)

GetSecureCookie returns given cookie value from request header with default secret string.

func (*Context) GetSuperSecureCookie

func (ctx *Context) GetSuperSecureCookie(secret, key string) (string, bool)

GetSuperSecureCookie returns given cookie value from request header with secret string.

func (*Context) HTML

func (ctx *Context) HTML(status int, name string, data ...interface{})

HTML calls Render.HTML but allows less arguments.

func (*Context) HTMLSet

func (ctx *Context) HTMLSet(status int, setName, tplName string, data ...interface{})

HTML calls Render.HTMLSet but allows less arguments.

func (*Context) Next

func (c *Context) Next()

func (*Context) Params

func (ctx *Context) Params(name string) string

Params returns value of given param name. e.g. ctx.Params(":uid") or ctx.Params("uid")

func (*Context) ParamsEscape

func (ctx *Context) ParamsEscape(name string) string

ParamsEscape returns escapred params result. e.g. ctx.ParamsEscape(":uname")

func (*Context) ParamsFloat64

func (ctx *Context) ParamsFloat64(name string) float64

ParamsFloat64 returns params result in int64 type. e.g. ctx.ParamsFloat64(":uid")

func (*Context) ParamsInt

func (ctx *Context) ParamsInt(name string) int

ParamsInt returns params result in int type. e.g. ctx.ParamsInt(":uid")

func (*Context) ParamsInt64

func (ctx *Context) ParamsInt64(name string) int64

ParamsInt64 returns params result in int64 type. e.g. ctx.ParamsInt64(":uid")

func (*Context) Query

func (ctx *Context) Query(name string) string

Query querys form parameter.

func (*Context) QueryEscape

func (ctx *Context) QueryEscape(name string) string

QueryEscape returns escapred query result.

func (*Context) QueryFloat64

func (ctx *Context) QueryFloat64(name string) float64

QueryFloat64 returns query result in float64 type.

func (*Context) QueryInt

func (ctx *Context) QueryInt(name string) int

QueryInt returns query result in int type.

func (*Context) QueryInt64

func (ctx *Context) QueryInt64(name string) int64

QueryInt64 returns query result in int64 type.

func (*Context) QueryStrings

func (ctx *Context) QueryStrings(name string) []string

QueryStrings returns a list of results by given query name.

func (*Context) Redirect

func (ctx *Context) Redirect(location string, status ...int)

func (*Context) RemoteAddr

func (ctx *Context) RemoteAddr() string

RemoteAddr returns more real IP address.

func (*Context) ServeContent

func (ctx *Context) ServeContent(name string, r io.ReadSeeker, params ...interface{})

ServeContent serves given content to response.

func (*Context) ServeFile

func (ctx *Context) ServeFile(file string, names ...string)

ServeFile serves given file to response.

func (*Context) SetCookie

func (ctx *Context) SetCookie(name string, value string, others ...interface{})

SetCookie sets given cookie value to response header.

func (*Context) SetParams

func (ctx *Context) SetParams(name, val string)

SetParams sets value of param with given name.

func (*Context) SetSecureCookie

func (ctx *Context) SetSecureCookie(name, value string, others ...interface{})

SetSecureCookie sets given cookie value to response header with default secret string.

func (*Context) SetSuperSecureCookie

func (ctx *Context) SetSuperSecureCookie(secret, name, value string, others ...interface{})

SetSuperSecureCookie sets given cookie value to response header with secret string.

func (*Context) Written

func (c *Context) Written() bool

type Delims

type Delims struct {
	// Left delimiter, defaults to {{
	Left string
	// Right delimiter, defaults to }}
	Right string
}

Delims represents a set of Left and Right delimiters for HTML template rendering

type HTMLOptions

type HTMLOptions struct {
	// Layout template name. Overrides Options.Layout.
	Layout string
}

HTMLOptions is a struct for overriding some rendering Options for specific HTML call

type Handle

type Handle func(http.ResponseWriter, *http.Request, Params)

Handle is a function that can be registered to a route to handle HTTP requests. Like http.HandlerFunc, but has a third parameter for the values of wildcards (variables).

type Handler

type Handler interface{}

Handler can be any callable function. Bigo attempts to inject services into the handler's argument list, and panics if an argument could not be fullfilled via dependency injection.

func Gziper

func Gziper() Handler

Gziper returns a Handler that adds gzip compression to all requests. Make sure to include the Gzip middleware above other middleware that alter the response body (like the render middleware).

func I18n

func I18n(options ...I18nOptions) Handler

I18n is a middleware provides localization layer for your application. Paramenter langs must be in the form of "en-US", "zh-CN", etc. Otherwise it may not recognize browser input.

func Recovery

func Recovery() Handler

Recovery returns a middleware that recovers from any panics and writes a 500 if there was one. While Martini is in development mode, Recovery will also output the panic as HTML.

func Renderer

func Renderer(options ...RenderOptions) Handler

Renderer is a Middleware that maps a macaron.Render service into the Macaron handler chain. An single variadic macaron.RenderOptions struct can be optionally provided to configure HTML rendering. The default directory for templates is "templates" and the default file extension is ".tmpl" and ".html".

If MACARON_ENV is set to "" or "development" then templates will be recompiled on every request. For more performance, set the MACARON_ENV environment variable to "production".

func Renderers

func Renderers(options RenderOptions, tplSets ...string) Handler

func ReqLogger

func ReqLogger() Handler

Logger returns a middleware handler that logs the request as it goes in and the response as it goes out.

func Secure

func Secure(opt SecureOptions) Handler

Secure is a middleware that helps setup a few basic security features. A single SecureOptions struct can be provided to configure which features should be enabled, and the ability to override a few of the default values.

func Static

func Static(directory string, staticOpt ...StaticOptions) Handler

Static returns a middleware handler that serves static files in the given directory.

func Statics

func Statics(opt StaticOptions, dirs ...string) Handler

Statics registers multiple static middleware handlers all at once.

type I18nOpt

type I18nOpt struct {
	Enable          bool     `json:"Enable"`          //是否开启
	SubUrl          string   `json:"SubUrl"`          //子目录,默认为空
	Directory       string   `json:"Directory"`       //存放本地化文件的目录,默认为 "conf/locale"
	CustomDirectory string   `json:"CustomDirectory"` //用于重载的本地化文件目录,默认为 "custom/conf/locale"
	Langs           []string `json:"Langs"`           //支持的语言,顺序是有意义的
	Names           []string `json:"Names"`           //语言的本地化名称,和上面一一对应
	Format          string   `json:"Format"`          //本地化文件命名风格,默认为 "locale_%s.ini"
	Parameter       string   `json:"Parameter"`       //指示当前语言的 URL 参数名,默认为 "lang"
	Redirect        bool     `json:"Redirect"`        //当通过 URL 参数指定语言时是否重定向,默认为 false
	TmplName        string   `json:"TmplName"`        //存放在模板中的本地化对象变量名称,默认为 "i18n"
}

本地化配置

type I18nOptions

type I18nOptions struct {
	// Suburl of path. Default is empty.
	SubURL string
	// Directory to load locale files. Default is "conf/locale"
	Directory string
	// Custom directory to overload locale files. Default is "custom/conf/locale"
	CustomDirectory string
	// Langauges that will be supported, order is meaningful.
	Langs []string
	// Human friendly names corresponding to Langs list.
	Names []string
	// Locale file naming style. Default is "locale_%s.ini".
	Format string
	// Name of language parameter name in URL. Default is "lang".
	Parameter string
	// Redirect when user uses get parameter to specify language.
	Redirect bool
	// Name that maps into template variable. Default is "i18n".
	TmplName string
}

I18nOptions represents a struct for specifying configuration options for the i18n middleware.

type ILocale

type ILocale interface {
	Language() string
	Tr(string, ...interface{}) string
}

Locale reprents a localization interface.

type KMap

type KMap map[string]interface{}

type LangType

type LangType struct {
	Lang, Name string
}

type Locale

type Locale struct {
	i18n.Locale
}

A Locale describles the information of localization.

func (Locale) Language

func (l Locale) Language() string

Language returns language current locale represents.

type LogLevel

type LogLevel int
const (
	LogLevelNone LogLevel = iota
	LogLevelInfo
	LogLevelDebug
	LogLevelError
)

type Logger

type Logger struct {
	*log.Logger
}

日志输出器

func DefaultLogger

func DefaultLogger() *Logger

默认日志输出器

func NewLogger

func NewLogger(out io.Writer, prefix string, flag int) *Logger

func (*Logger) Log

func (l *Logger) Log(level LogLevel, a ...interface{})

输出日志,level为日志级别

func (*Logger) LogDebug

func (l *Logger) LogDebug(a ...interface{})

调试日志输出,第一个参数可以是format

func (*Logger) LogError

func (l *Logger) LogError(a ...interface{})

错误日志输出,第一个参数可以是format

func (*Logger) LogInfo

func (l *Logger) LogInfo(a ...interface{})

普通信息日志输出,第一个参数可以是format

type LoggerWriter

type LoggerWriter struct {
	io.Writer
	// contains filtered or unexported fields
}

log输出模块

func (*LoggerWriter) Write

func (log *LoggerWriter) Write(p []byte) (n int, err error)

type Params

type Params map[string]string

type Render

type Render interface {
	http.ResponseWriter
	RW() http.ResponseWriter

	JSON(int, interface{})
	JSONString(interface{}) (string, error)
	RawData(int, []byte)
	RenderData(int, []byte)
	HTML(int, string, interface{}, ...HTMLOptions)
	HTMLSet(int, string, string, interface{}, ...HTMLOptions)
	HTMLSetString(string, string, interface{}, ...HTMLOptions) (string, error)
	HTMLString(string, interface{}, ...HTMLOptions) (string, error)
	HTMLSetBytes(string, string, interface{}, ...HTMLOptions) ([]byte, error)
	HTMLBytes(string, interface{}, ...HTMLOptions) ([]byte, error)
	XML(int, interface{})
	Error(int, ...string)
	Status(int)
	SetTemplatePath(string, string)
	HasTemplateSet(string) bool
}

type RenderOptions

type RenderOptions struct {
	// Directory to load templates. Default is "templates".
	Directory string
	// Layout template name. Will not render a layout if "". Default is to "".
	Layout string
	// Extensions to parse template files from. Defaults are [".tmpl", ".html"].
	Extensions []string
	// Funcs is a slice of FuncMaps to apply to the template upon compilation. This is useful for helper functions. Default is [].
	Funcs []template.FuncMap
	// Delims sets the action delimiters to the specified strings in the Delims struct.
	Delims Delims
	// Appends the given charset to the Content-Type header. Default is "UTF-8".
	Charset string
	// Outputs human readable JSON.
	IndentJSON bool
	// Outputs human readable XML.
	IndentXML bool
	// Prefixes the JSON output with the given bytes.
	PrefixJSON []byte
	// Prefixes the XML output with the given bytes.
	PrefixXML []byte
	// Allows changing of output to XHTML instead of HTML. Default is "text/html"
	HTMLContentType string
	// TemplateFileSystem is the interface for supporting any implmentation of template file system.
	TemplateFileSystem
}

RenderOptions represents a struct for specifying configuration options for the Render middleware.

type Request

type Request struct {
	*http.Request
}

Request represents an HTTP request received by a server or to be sent by a client.

func (*Request) Body

func (r *Request) Body() *RequestBody

type RequestBody

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

RequestBody represents a request body.

func (*RequestBody) Bytes

func (rb *RequestBody) Bytes() ([]byte, error)

Bytes reads and returns content of request body in bytes.

func (*RequestBody) ReadCloser

func (rb *RequestBody) ReadCloser() io.ReadCloser

ReadCloser returns a ReadCloser for request body.

func (*RequestBody) String

func (rb *RequestBody) String() (string, error)

String reads and returns content of request body in string.

type ResponseWriter

type ResponseWriter interface {
	http.ResponseWriter
	http.Flusher
	// Status returns the status code of the response or 0 if the response has not been written.
	Status() int
	// Written returns whether or not the ResponseWriter has been written.
	Written() bool
	// Size returns the size of the response body.
	Size() int
	// Before allows for a function to be called before the ResponseWriter has been written to. This is
	// useful for setting headers or any other operations that must happen before a response has been written.
	Before(BeforeFunc)
}

ResponseWriter is a wrapper around http.ResponseWriter that provides extra information about the response. It is recommended that middleware handlers use this construct to wrap a responsewriter if the functionality calls for it.

func NewResponseWriter

func NewResponseWriter(rw http.ResponseWriter) ResponseWriter

NewResponseWriter creates a ResponseWriter that wraps an http.ResponseWriter

type ReturnHandler

type ReturnHandler func(*Context, []reflect.Value)

ReturnHandler is a service that Martini provides that is called when a route handler returns something. The ReturnHandler is responsible for writing to the ResponseWriter based on the values that are passed into this function.

type Router

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

Router represents a Bigo router layer.

func NewRouter

func NewRouter() *Router

func (*Router) Any

func (r *Router) Any(pattern string, h ...Handler)

Any is a shortcut for r.Handle("*", pattern, handlers)

func (*Router) Combo

func (r *Router) Combo(pattern string, h ...Handler) *ComboRouter

Combo returns a combo router.

func (*Router) Delete

func (r *Router) Delete(pattern string, h ...Handler)

Delete is a shortcut for r.Handle("DELETE", pattern, handlers)

func (*Router) Get

func (r *Router) Get(pattern string, h ...Handler)

Get is a shortcut for r.Handle("GET", pattern, handlers)

func (*Router) Group

func (r *Router) Group(pattern string, fn func(), h ...Handler)

func (*Router) Handle

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

Handle registers a new request handle with the given pattern, method and handlers.

func (*Router) Head

func (r *Router) Head(pattern string, h ...Handler)

Head is a shortcut for r.Handle("HEAD", pattern, handlers)

func (*Router) NotFound

func (r *Router) NotFound(handlers ...Handler)

Configurable http.HandlerFunc which is called when no matching route is found. If it is not set, http.NotFound is used. Be sure to set 404 response code in your handler.

func (*Router) Options

func (r *Router) Options(pattern string, h ...Handler)

Options is a shortcut for r.Handle("OPTIONS", pattern, handlers)

func (*Router) Patch

func (r *Router) Patch(pattern string, h ...Handler)

Patch is a shortcut for r.Handle("PATCH", pattern, handlers)

func (*Router) Post

func (r *Router) Post(pattern string, h ...Handler)

Post is a shortcut for r.Handle("POST", pattern, handlers)

func (*Router) Put

func (r *Router) Put(pattern string, h ...Handler)

Put is a shortcut for r.Handle("PUT", pattern, handlers)

func (*Router) Route

func (r *Router) Route(pattern, methods string, h ...Handler)

Route is a shortcut for same handlers but different HTTP methods.

Example:

m.Route("/", "GET,POST", h)

func (*Router) ServeHTTP

func (r *Router) ServeHTTP(rw http.ResponseWriter, req *http.Request)

type SecureOptions

type SecureOptions struct {
	// AllowedHosts is a list of fully qualified domain names that are allowed. Default is empty list, which allows any and all host names.
	AllowedHosts []string
	// If SSLRedirect is set to true, then only allow https requests. Default is false.
	SSLRedirect bool
	// SSLHost is the host name that is used to redirect http requests to https. Default is "", which indicates to use the same host.
	SSLHost string
	// SSLProxyHeaders is set of header keys with associated values that would indicate a valid https request. Useful when using Nginx: `map[string]string{"X-Forwarded-Proto": "https"}`. Default is blank map.
	SSLProxyHeaders map[string]string
	// STSSeconds is the max-age of the Strict-Transport-Security header. Default is 0, which would NOT include the header.
	STSSeconds int64
	// If STSIncludeSubdomains is set to true, the `includeSubdomains` will be appended to the Strict-Transport-Security header. Default is false.
	STSIncludeSubdomains bool
	// If FrameDeny is set to true, adds the X-Frame-Options header with the value of `DENY`. Default is false.
	FrameDeny bool
	// CustomFrameOptionsValue allows the X-Frame-Options header value to be set with a custom value. This overrides the FrameDeny option.
	CustomFrameOptionsValue string
	// If ContentTypeNosniff is true, adds the X-Content-Type-Options header with the value `nosniff`. Default is false.
	ContentTypeNosniff bool
	// If BrowserXssFilter is true, adds the X-XSS-Protection header with the value `1; mode=block`. Default is false.
	BrowserXssFilter bool
	// ContentSecurityPolicy allows the Content-Security-Policy header value to be set with a custom value. Default is "".
	ContentSecurityPolicy string
	// When developing, the AllowedHosts, SSL, and STS options can cause some unwanted effects. Usually testing happens on http, not https, and one localhost, not your production domain... we check `if Env == Prod`.
	// If you would like your development environment to mimic production with complete Host blocking, SSL redirects, and STS headers, set this to true. Default if false.
	DisableProdCheck bool
}

SecureOptions is a struct for specifying configuration options for the secure.Secure middleware.

type StaticOpt

type StaticOpt struct {
	Path        string `json:"Path"`        //静态目录的路径
	Prefix      string `json:"Prefix"`      //此目录在url中的前缀,如果不设置则为/
	SkipLogging bool   `json:"SkipLogging"` //默认在DEV,TEST模式下为false,在PROD模式下为true. 是否跳过log输出
	IndexFile   string `json:"IndexFile"`   //如果指定,则以此文件为索引文件
}

静态文件配置

type StaticOptions

type StaticOptions struct {
	// Prefix is the optional prefix used to serve the static directory content
	Prefix string
	// SkipLogging will disable [Static] log messages when a static file is served.
	SkipLogging bool
	// IndexFile defines which file to serve as index if it exists.
	IndexFile string
	// Expires defines which user-defined function to use for producing a HTTP Expires Header
	// https://developers.google.com/speed/docs/insights/LeverageBrowserCaching
	Expires func() string
	// FileSystem is the interface for supporting any implmentation of file system.
	FileSystem http.FileSystem
}

StaticOptions is a struct for specifying configuration options for the macaron.Static middleware.

type SubConfig

type SubConfig map[string]interface{}

type TemplateFile

type TemplateFile interface {
	Name() string
	Data() []byte
	Ext() string
}

TemplateFile represents a interface of template file that has name and can be read.

type TemplateFileSystem

type TemplateFileSystem interface {
	ListFiles() []TemplateFile
}

TemplateFileSystem represents a interface of template file system that able to list all files.

type TmplOpt

type TmplOpt struct {
	Enable          bool     `json:"Enable"`          //是否启动模板引擎,默认为false
	Directory       string   `json:"Directory"`       //模板文件目录,默认为 "views"
	Extensions      []string `json:"Extensions"`      //模板文件后缀,默认为 [".tmpl", ".html"]
	Delims          []string `json:"Delims"`          //模板语法分隔符,默认为 ["{{", "}}"]
	Charset         string   `json:"Charset"`         //追加的 Content-Type 头信息,默认为 "UTF-8"
	IndentJSON      bool     `json:"IndentJSON"`      //渲染具有缩进格式的 JSON,默认为不缩进
	IndentXML       bool     `json:"IndentXML"`       //渲染具有缩进格式的 XML,默认为不缩进
	HTMLContentType string   `json:"HTMLContentType"` //默认为 "text/html"
}

模板引擎配置

type TplFile

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

TplFile implements TemplateFile interface.

func NewTplFile

func NewTplFile(name string, data []byte, ext string) *TplFile

NewTplFile cerates new template file with given name and data.

func (*TplFile) Data

func (f *TplFile) Data() []byte

func (*TplFile) Ext

func (f *TplFile) Ext() string

func (*TplFile) Name

func (f *TplFile) Name() string

type TplFileSystem

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

TplFileSystem implements TemplateFileSystem interface.

func NewTemplateFileSystem

func NewTemplateFileSystem(opt RenderOptions, omitData bool) TplFileSystem

NewTemplateFileSystem creates new template file system with given options.

func (TplFileSystem) ListFiles

func (fs TplFileSystem) ListFiles() []TemplateFile

type TplRender

type TplRender struct {
	http.ResponseWriter

	Opt             *RenderOptions
	CompiledCharset string
	// contains filtered or unexported fields
}

func (*TplRender) Error

func (r *TplRender) Error(status int, message ...string)

Error writes the given HTTP status to the current ResponseWriter

func (TplRender) Get

func (ts TplRender) Get(name string) *template.Template

func (TplRender) GetDir

func (ts TplRender) GetDir(name string) string

func (*TplRender) HTML

func (r *TplRender) HTML(status int, name string, data interface{}, htmlOpt ...HTMLOptions)

func (*TplRender) HTMLBytes

func (r *TplRender) HTMLBytes(name string, data interface{}, htmlOpt ...HTMLOptions) ([]byte, error)

func (*TplRender) HTMLSet

func (r *TplRender) HTMLSet(status int, setName, tplName string, data interface{}, htmlOpt ...HTMLOptions)

func (*TplRender) HTMLSetBytes

func (r *TplRender) HTMLSetBytes(setName, tplName string, data interface{}, htmlOpt ...HTMLOptions) ([]byte, error)

func (*TplRender) HTMLSetString

func (r *TplRender) HTMLSetString(setName, tplName string, data interface{}, htmlOpt ...HTMLOptions) (string, error)

func (*TplRender) HTMLString

func (r *TplRender) HTMLString(name string, data interface{}, htmlOpt ...HTMLOptions) (string, error)

func (*TplRender) HasTemplateSet

func (r *TplRender) HasTemplateSet(name string) bool

func (*TplRender) JSON

func (r *TplRender) JSON(status int, v interface{})

func (*TplRender) JSONString

func (r *TplRender) JSONString(v interface{}) (string, error)

func (*TplRender) RW

func (r *TplRender) RW() http.ResponseWriter

func (*TplRender) RawData

func (r *TplRender) RawData(status int, v []byte)

func (*TplRender) RenderData

func (r *TplRender) RenderData(status int, v []byte)

func (TplRender) Set

func (ts TplRender) Set(name string, opt *RenderOptions) *template.Template

func (*TplRender) SetTemplatePath

func (r *TplRender) SetTemplatePath(setName, dir string)

func (*TplRender) Status

func (r *TplRender) Status(status int)

func (*TplRender) XML

func (r *TplRender) XML(status int, v interface{})

type Tree

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

Tree represents a router tree for Macaron instance.

func NewTree

func NewTree() *Tree

NewTree initializes and returns a router tree.

func (*Tree) AddRouter

func (t *Tree) AddRouter(pattern string, handle Handle)

AddRouter adds a new route to router tree.

func (*Tree) Match

func (t *Tree) Match(pattern string) (Handle, Params)

Match returns Handle and params if any route is matched.

Directories

Path Synopsis
Package inject provides utilities for mapping and injecting dependencies in various ways.
Package inject provides utilities for mapping and injecting dependencies in various ways.
Package com is an open source project for commonly used functions for the Go programming language.
Package com is an open source project for commonly used functions for the Go programming language.
Package websockets is a middleware that provides WebSockets channels binding for bigo.
Package websockets is a middleware that provides WebSockets channels binding for bigo.

Jump to

Keyboard shortcuts

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