ghttp

package
v1.12.0 Latest Latest
Warning

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

Go to latest
Published: Mar 29, 2020 License: MIT Imports: 63 Imported by: 521

Documentation

Overview

Package ghttp provides powerful http server and simple client implements.

Index

Constants

View Source
const (
	SERVER_STATUS_STOPPED = 0
	SERVER_STATUS_RUNNING = 1
	HOOK_BEFORE_SERVE     = "HOOK_BEFORE_SERVE"
	HOOK_AFTER_SERVE      = "HOOK_AFTER_SERVE"
	HOOK_BEFORE_OUTPUT    = "HOOK_BEFORE_OUTPUT"
	HOOK_AFTER_OUTPUT     = "HOOK_AFTER_OUTPUT"
	HTTP_METHODS          = "GET,PUT,POST,DELETE,PATCH,HEAD,CONNECT,OPTIONS,TRACE"
)
View Source
const (
	URI_TYPE_DEFAULT  = 0 // Method name to URI converting type, which converts name to its lower case and joins the words using char '-'.
	URI_TYPE_FULLNAME = 1 // Method name to URI converting type, which does no converting to the method name.
	URI_TYPE_ALLLOWER = 2 // Method name to URI converting type, which converts name to its lower case.
	URI_TYPE_CAMEL    = 3 // Method name to URI converting type, which converts name to its camel case.
)
View Source
const (
	// TextMessage denotes a text data message. The text message payload is
	// interpreted as UTF-8 encoded text data.
	WS_MSG_TEXT = websocket.TextMessage

	// BinaryMessage denotes a binary data message.
	WS_MSG_BINARY = websocket.BinaryMessage

	// CloseMessage denotes a close control message. The optional message
	// payload contains a numeric code and text. Use the FormatCloseMessage
	// function to format a close message payload.
	WS_MSG_CLOSE = websocket.CloseMessage

	// PingMessage denotes a ping control message. The optional message payload
	// is UTF-8 encoded text.
	WS_MSG_PING = websocket.PingMessage

	// PongMessage denotes a pong control message. The optional message payload
	// is UTF-8 encoded text.
	WS_MSG_PONG = websocket.PongMessage
)

Variables

This section is empty.

Functions

func BuildParams

func BuildParams(params interface{}, noUrlEncode ...bool) (encodedParamStr string)

BuildParams builds the request string for the http client. The <params> can be type of: string/[]byte/map/struct/*struct.

The optional parameter <noUrlEncode> specifies whether ignore the url encoding for the data.

func ConnectBytes

func ConnectBytes(url string, data ...interface{}) []byte

ConnectBytes is a convenience method for sending CONNECT request, which retrieves and returns the result content as bytes and automatically closes response object.

func ConnectContent

func ConnectContent(url string, data ...interface{}) string

ConnectContent is a convenience method for sending CONNECT request, which retrieves and returns the result content and automatically closes response object.

func DeleteBytes

func DeleteBytes(url string, data ...interface{}) []byte

DeleteBytes is a convenience method for sending DELETE request, which retrieves and returns the result content as bytes and automatically closes response object.

func DeleteContent

func DeleteContent(url string, data ...interface{}) string

DeleteContent is a convenience method for sending DELETE request, which retrieves and returns the result content and automatically closes response object.

func GetBytes

func GetBytes(url string, data ...interface{}) []byte

GetBytes is a convenience method for sending GET request, which retrieves and returns the result content as bytes and automatically closes response object.

func GetContent

func GetContent(url string, data ...interface{}) string

GetContent is a convenience method for sending GET request, which retrieves and returns the result content and automatically closes response object.

func HeadBytes

func HeadBytes(url string, data ...interface{}) []byte

HeadBytes is a convenience method for sending HEAD request, which retrieves and returns the result content as bytes and automatically closes response object.

func HeadContent

func HeadContent(url string, data ...interface{}) string

HeadContent is a convenience method for sending HEAD request, which retrieves and returns the result content and automatically closes response object.

func IsExitError

func IsExitError(err interface{}) bool

主要用于开发者在HTTP处理中自定义异常捕获时,判断捕获的异常是否Server抛出的自定义退出异常

func OptionsBytes

func OptionsBytes(url string, data ...interface{}) []byte

OptionsBytes is a convenience method for sending OPTIONS request, which retrieves and returns the result content as bytes and automatically closes response object.

func OptionsContent

func OptionsContent(url string, data ...interface{}) string

OptionsContent is a convenience method for sending OPTIONS request, which retrieves and returns the result content and automatically closes response object.

func PatchBytes

func PatchBytes(url string, data ...interface{}) []byte

PatchBytes is a convenience method for sending PATCH request, which retrieves and returns the result content as bytes and automatically closes response object.

func PatchContent

func PatchContent(url string, data ...interface{}) string

PatchContent is a convenience method for sending PATCH request, which retrieves and returns the result content and automatically closes response object.

func PostBytes

func PostBytes(url string, data ...interface{}) []byte

PostBytes is a convenience method for sending POST request, which retrieves and returns the result content as bytes and automatically closes response object.

func PostContent

func PostContent(url string, data ...interface{}) string

PostContent is a convenience method for sending POST request, which retrieves and returns the result content and automatically closes response object.

func PutBytes

func PutBytes(url string, data ...interface{}) []byte

PutBytes is a convenience method for sending PUT request, which retrieves and returns the result content as bytes and automatically closes response object.

func PutContent

func PutContent(url string, data ...interface{}) string

PutContent is a convenience method for sending PUT request, which retrieves and returns the result content and automatically closes response object.

func RequestBytes

func RequestBytes(method string, url string, data ...interface{}) []byte

RequestBytes is a convenience method for sending custom http method request, which retrieves and returns the result content as bytes and automatically closes response object.

func RequestContent

func RequestContent(method string, url string, data ...interface{}) string

RequestContent is a convenience method for sending custom http method request, which retrieves and returns the result content and automatically closes response object.

func RestartAllServer

func RestartAllServer(newExeFilePath ...string) error

重启Web Server,参数支持自定义重启的可执行文件路径,不传递时默认和原有可执行文件路径一致。 针对*niux系统: 平滑重启 针对windows : 完整重启

func SetGraceful

func SetGraceful(enabled bool)

是否开启平滑重启特性

func ShutdownAllServer

func ShutdownAllServer() error

关闭所有的WebServer

func TraceBytes

func TraceBytes(url string, data ...interface{}) []byte

TraceBytes is a convenience method for sending TRACE request, which retrieves and returns the result content as bytes and automatically closes response object.

func TraceContent

func TraceContent(url string, data ...interface{}) string

TraceContent is a convenience method for sending TRACE request, which retrieves and returns the result content and automatically closes response object.

func Wait

func Wait()

Wait blocks to wait for all servers done. It's commonly used in multiple servers situation.

Types

type BodyReadCloser added in v1.11.5

type BodyReadCloser struct {
	*bytes.Reader
}

BodyReadCloser implements the io.ReadCloser interface which is used for reading request body content multiple times.

func (*BodyReadCloser) Close added in v1.11.5

func (b *BodyReadCloser) Close() error

Close implements the io.ReadCloser interface.

type CORSOptions

type CORSOptions struct {
	AllowDomain      []string // Used for allowing requests from custom domains
	AllowOrigin      string   // Access-Control-Allow-Origin
	AllowCredentials string   // Access-Control-Allow-Credentials
	ExposeHeaders    string   // Access-Control-Expose-Headers
	MaxAge           int      // Access-Control-Max-Age
	AllowMethods     string   // Access-Control-Allow-Methods
	AllowHeaders     string   // Access-Control-Allow-Headers
}

CORSOptions is the options for CORS feature. See https://www.w3.org/TR/cors/ .

type Client

type Client struct {
	http.Client // Underlying HTTP Client.
	// contains filtered or unexported fields
}

Client is the HTTP client for HTTP request management.

func NewClient

func NewClient() *Client

NewClient creates and returns a new HTTP client object.

func (*Client) BasicAuth

func (c *Client) BasicAuth(user, pass string) *Client

BasicAuth is a chaining function, which sets HTTP basic authentication information for next request.

func (*Client) Clone

func (c *Client) Clone() *Client

Clone clones current client and returns a new one.

func (*Client) Connect

func (c *Client) Connect(url string, data ...interface{}) (*ClientResponse, error)

Connect send CONNECT request and returns the response object. Note that the response object MUST be closed if it'll be never used.

func (*Client) ConnectBytes

func (c *Client) ConnectBytes(url string, data ...interface{}) []byte

ConnectBytes sends a CONNECT request, retrieves and returns the result content as bytes.

func (*Client) ConnectContent

func (c *Client) ConnectContent(url string, data ...interface{}) string

func (*Client) ContentJson added in v1.12.0

func (c *Client) ContentJson() *Client

ContentJson is a chaining function, which sets the HTTP content type as "application/json" for the next request.

Note that it also checks and encodes the parameter to JSON format automatically.

func (*Client) ContentType added in v1.12.0

func (c *Client) ContentType(contentType string) *Client

ContentType is a chaining function, which sets HTTP content type for the next request.

func (*Client) ContentXml added in v1.12.0

func (c *Client) ContentXml() *Client

ContentXml is a chaining function, which sets the HTTP content type as "application/xml" for the next request.

Note that it also checks and encodes the parameter to XML format automatically.

func (*Client) Cookie added in v1.12.0

func (c *Client) Cookie(m map[string]string) *Client

Cookie is a chaining function, which sets cookie items with map for next request.

func (*Client) Ctx added in v1.12.0

func (c *Client) Ctx(ctx context.Context) *Client

Ctx is a chaining function, which sets context for next request of this client.

func (*Client) Delete

func (c *Client) Delete(url string, data ...interface{}) (*ClientResponse, error)

Delete send DELETE request and returns the response object. Note that the response object MUST be closed if it'll be never used.

func (*Client) DeleteBytes

func (c *Client) DeleteBytes(url string, data ...interface{}) []byte

DeleteBytes sends a DELETE request, retrieves and returns the result content as bytes.

func (*Client) DeleteContent

func (c *Client) DeleteContent(url string, data ...interface{}) string

func (*Client) DoRequest

func (c *Client) DoRequest(method, url string, data ...interface{}) (resp *ClientResponse, err error)

DoRequest sends request with given HTTP method and data and returns the response object. Note that the response object MUST be closed if it'll be never used.

Note that it uses "multipart/form-data" as its Content-Type if it contains file uploading, else it uses "application/x-www-form-urlencoded". It also automatically detects the post content for JSON format, and for that it automatically sets the Content-Type as "application/json".

func (*Client) Get

func (c *Client) Get(url string, data ...interface{}) (*ClientResponse, error)

Get send GET request and returns the response object. Note that the response object MUST be closed if it'll be never used.

func (*Client) GetBytes

func (c *Client) GetBytes(url string, data ...interface{}) []byte

GetBytes sends a GET request, retrieves and returns the result content as bytes.

func (*Client) GetContent

func (c *Client) GetContent(url string, data ...interface{}) string

func (*Client) Head

func (c *Client) Head(url string, data ...interface{}) (*ClientResponse, error)

Head send HEAD request and returns the response object. Note that the response object MUST be closed if it'll be never used.

func (*Client) HeadBytes

func (c *Client) HeadBytes(url string, data ...interface{}) []byte

HeadBytes sends a HEAD request, retrieves and returns the result content as bytes.

func (*Client) HeadContent

func (c *Client) HeadContent(url string, data ...interface{}) string

func (*Client) Header added in v1.12.0

func (c *Client) Header(m map[string]string) *Client

Header is a chaining function, which sets custom HTTP headers with map for next request.

func (*Client) HeaderRaw added in v1.12.0

func (c *Client) HeaderRaw(headers string) *Client

Header is a chaining function, which sets custom HTTP header using raw string for next request.

func (*Client) Options

func (c *Client) Options(url string, data ...interface{}) (*ClientResponse, error)

Options send OPTIONS request and returns the response object. Note that the response object MUST be closed if it'll be never used.

func (*Client) OptionsBytes

func (c *Client) OptionsBytes(url string, data ...interface{}) []byte

OptionsBytes sends a OPTIONS request, retrieves and returns the result content as bytes.

func (*Client) OptionsContent

func (c *Client) OptionsContent(url string, data ...interface{}) string

func (*Client) Patch

func (c *Client) Patch(url string, data ...interface{}) (*ClientResponse, error)

Patch send PATCH request and returns the response object. Note that the response object MUST be closed if it'll be never used.

func (*Client) PatchBytes

func (c *Client) PatchBytes(url string, data ...interface{}) []byte

PatchBytes sends a PATCH request, retrieves and returns the result content as bytes.

func (*Client) PatchContent

func (c *Client) PatchContent(url string, data ...interface{}) string

func (*Client) Post

func (c *Client) Post(url string, data ...interface{}) (*ClientResponse, error)

Post sends request using HTTP method POST and returns the response object. Note that the response object MUST be closed if it'll be never used.

func (*Client) PostBytes

func (c *Client) PostBytes(url string, data ...interface{}) []byte

PostBytes sends a POST request, retrieves and returns the result content as bytes.

func (*Client) PostContent

func (c *Client) PostContent(url string, data ...interface{}) string

func (*Client) Put

func (c *Client) Put(url string, data ...interface{}) (*ClientResponse, error)

Put send PUT request and returns the response object. Note that the response object MUST be closed if it'll be never used.

func (*Client) PutBytes

func (c *Client) PutBytes(url string, data ...interface{}) []byte

PutBytes sends a PUT request, retrieves and returns the result content as bytes.

func (*Client) PutContent

func (c *Client) PutContent(url string, data ...interface{}) string

func (*Client) RequestBytes

func (c *Client) RequestBytes(method string, url string, data ...interface{}) []byte

RequestBytes sends request using given HTTP method and data, retrieves returns the result as bytes. It reads and closes the response object internally automatically.

func (*Client) RequestContent

func (c *Client) RequestContent(method string, url string, data ...interface{}) string

func (*Client) SetBasicAuth

func (c *Client) SetBasicAuth(user, pass string) *Client

SetBasicAuth sets HTTP basic authentication information for the client.

func (*Client) SetBrowserMode

func (c *Client) SetBrowserMode(enabled bool) *Client

SetBrowserMode enables browser mode of the client. When browser mode is enabled, it automatically saves and sends cookie content from and to server.

func (*Client) SetContentType added in v1.10.0

func (c *Client) SetContentType(contentType string) *Client

SetContentType sets HTTP content type for the client.

func (*Client) SetCookie

func (c *Client) SetCookie(key, value string) *Client

SetCookie sets a cookie pair for the client.

func (*Client) SetCookieMap

func (c *Client) SetCookieMap(m map[string]string) *Client

SetCookieMap sets cookie items with map.

func (*Client) SetCtx added in v1.12.0

func (c *Client) SetCtx(ctx context.Context) *Client

SetCtx sets context for each request of this client.

func (*Client) SetHeader

func (c *Client) SetHeader(key, value string) *Client

SetHeader sets a custom HTTP header pair for the client.

func (*Client) SetHeaderMap added in v1.10.0

func (c *Client) SetHeaderMap(m map[string]string) *Client

SetHeaderMap sets custom HTTP headers with map.

func (*Client) SetHeaderRaw

func (c *Client) SetHeaderRaw(headers string) *Client

SetHeaderRaw sets custom HTTP header using raw string.

func (*Client) SetPrefix

func (c *Client) SetPrefix(prefix string) *Client

SetPrefix sets the request server URL prefix.

func (*Client) SetRetry

func (c *Client) SetRetry(retryCount int, retryInterval int) *Client

SetRetry sets retry count and interval.

func (*Client) SetTimeout added in v1.12.0

func (c *Client) SetTimeout(t time.Duration) *Client

SetTimeOut sets the request timeout for the client.

func (*Client) Timeout added in v1.12.0

func (c *Client) Timeout(t time.Duration) *Client

TimeOut is a chaining function, which sets the timeout for next request.

func (*Client) Trace

func (c *Client) Trace(url string, data ...interface{}) (*ClientResponse, error)

Trace send TRACE request and returns the response object. Note that the response object MUST be closed if it'll be never used.

func (*Client) TraceBytes

func (c *Client) TraceBytes(url string, data ...interface{}) []byte

TraceBytes sends a TRACE request, retrieves and returns the result content as bytes.

func (*Client) TraceContent

func (c *Client) TraceContent(url string, data ...interface{}) string

type ClientResponse

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

ClientResponse is the struct for client request response.

func Connect

func Connect(url string, data ...interface{}) (*ClientResponse, error)

Connect is a convenience method for sending CONNECT request. NOTE that remembers CLOSING the response object when it'll never be used.

func Delete

func Delete(url string, data ...interface{}) (*ClientResponse, error)

Delete is a convenience method for sending DELETE request. NOTE that remembers CLOSING the response object when it'll never be used.

func DoRequest

func DoRequest(method, url string, data ...interface{}) (*ClientResponse, error)

DoRequest is a convenience method for sending custom http method request. NOTE that remembers CLOSING the response object when it'll never be used.

func Get

func Get(url string, data ...interface{}) (*ClientResponse, error)

Get is a convenience method for sending GET request. NOTE that remembers CLOSING the response object when it'll never be used.

func Head(url string, data ...interface{}) (*ClientResponse, error)

Head is a convenience method for sending HEAD request. NOTE that remembers CLOSING the response object when it'll never be used.

func Options

func Options(url string, data ...interface{}) (*ClientResponse, error)

Options is a convenience method for sending OPTIONS request. NOTE that remembers CLOSING the response object when it'll never be used.

func Patch

func Patch(url string, data ...interface{}) (*ClientResponse, error)

Patch is a convenience method for sending PATCH request. NOTE that remembers CLOSING the response object when it'll never be used.

func Post

func Post(url string, data ...interface{}) (*ClientResponse, error)

Post is a convenience method for sending POST request. NOTE that remembers CLOSING the response object when it'll never be used.

func Put

func Put(url string, data ...interface{}) (*ClientResponse, error)

Put is a convenience method for sending PUT request. NOTE that remembers CLOSING the response object when it'll never be used.

func Trace

func Trace(url string, data ...interface{}) (*ClientResponse, error)

Trace is a convenience method for sending TRACE request. NOTE that remembers CLOSING the response object when it'll never be used.

func (*ClientResponse) Close

func (r *ClientResponse) Close() error

Close closes the response when it will never be used.

func (*ClientResponse) GetCookie

func (r *ClientResponse) GetCookie(key string) string

GetCookie retrieves and returns the cookie value of specified <key>.

func (*ClientResponse) GetCookieMap added in v1.12.0

func (r *ClientResponse) GetCookieMap() map[string]string

GetCookieMap retrieves and returns a copy of current cookie values map.

func (*ClientResponse) ReadAll

func (r *ClientResponse) ReadAll() []byte

ReadAll retrieves and returns the response content as []byte.

func (*ClientResponse) ReadAllString

func (r *ClientResponse) ReadAllString() string

ReadAllString retrieves and returns the response content as string.

type Controller

type Controller interface {
	Init(*Request)
	Shut()
}

Controller is the base struct for controller.

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

COOKIE对象,非并发安全。

func GetCookie

func GetCookie(r *Request) *Cookie

获取或者创建一个COOKIE对象,与传入的请求对应(延迟初始化)

func (*Cookie) Contains

func (c *Cookie) Contains(key string) bool

判断Cookie中是否存在制定键名(并且没有过期)

func (*Cookie) Get

func (c *Cookie) Get(key string, def ...string) string

查询cookie

func (*Cookie) GetSessionId

func (c *Cookie) GetSessionId() string

获得客户端提交的SessionId

func (*Cookie) Map

func (c *Cookie) Map() map[string]string

获取所有的Cookie并构造成map[string]string返回.

func (*Cookie) Output

func (c *Cookie) Output()

输出到客户端

func (*Cookie) Remove

func (c *Cookie) Remove(key string)

删除COOKIE,使用默认的domain&path

func (*Cookie) RemoveCookie

func (c *Cookie) RemoveCookie(key, domain, path string)

标记该cookie在对应的域名和路径失效 删除cookie的重点是需要通知浏览器客户端cookie已过期

func (*Cookie) Set

func (c *Cookie) Set(key, value string)

设置cookie,使用默认参数

func (*Cookie) SetCookie

func (c *Cookie) SetCookie(key, value, domain, path string, maxAge time.Duration, httpOnly ...bool)

设置cookie,带详细cookie参数

func (*Cookie) SetSessionId

func (c *Cookie) SetSessionId(id string)

设置SessionId到Cookie中

type CookieItem

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

cookie项

type Domain

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

域名管理器对象

func (*Domain) BindController

func (d *Domain) BindController(pattern string, c Controller, methods ...string)

func (*Domain) BindControllerMethod

func (d *Domain) BindControllerMethod(pattern string, c Controller, method string)

func (*Domain) BindControllerRest

func (d *Domain) BindControllerRest(pattern string, c Controller)

func (*Domain) BindHandler

func (d *Domain) BindHandler(pattern string, handler HandlerFunc)

func (*Domain) BindHookHandler

func (d *Domain) BindHookHandler(pattern string, hook string, handler HandlerFunc)

func (*Domain) BindHookHandlerByMap

func (d *Domain) BindHookHandlerByMap(pattern string, hookmap map[string]HandlerFunc)

func (*Domain) BindMiddleware

func (d *Domain) BindMiddleware(pattern string, handlers ...HandlerFunc)

func (*Domain) BindMiddlewareDefault added in v1.10.0

func (d *Domain) BindMiddlewareDefault(handlers ...HandlerFunc)

func (*Domain) BindObject

func (d *Domain) BindObject(pattern string, obj interface{}, methods ...string)

func (*Domain) BindObjectMethod

func (d *Domain) BindObjectMethod(pattern string, obj interface{}, method string)

func (*Domain) BindObjectRest

func (d *Domain) BindObjectRest(pattern string, obj interface{})

func (*Domain) BindStatusHandler

func (d *Domain) BindStatusHandler(status int, handler HandlerFunc)

func (*Domain) BindStatusHandlerByMap

func (d *Domain) BindStatusHandlerByMap(handlerMap map[int]HandlerFunc)

func (*Domain) Group

func (d *Domain) Group(prefix string, groups ...func(group *RouterGroup)) *RouterGroup

Group creates and returns a RouterGroup object, which is bound to a specified domain.

func (*Domain) Use added in v1.11.5

func (d *Domain) Use(handlers ...HandlerFunc)

type GroupItem

type GroupItem = []interface{}

GroupItem is item for router group.

type HandlerFunc

type HandlerFunc = func(r *Request)

Request handler function.

type Middleware

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

Middleware is the plugin for request workflow management.

func (*Middleware) Next

func (m *Middleware) Next()

Next calls the next workflow handler.

type Plugin added in v1.11.4

type Plugin interface {
	Name() string            // Name returns the name of the plugin.
	Author() string          // Author returns the author of the plugin.
	Version() string         // Version returns the version of the plugin, like "v1.0.0".
	Description() string     // Description returns the description of the plugin.
	Install(s *Server) error // Install installs the plugin before server starts.
	Remove() error           // Remove removes the plugin.
}

Plugin is the interface for server plugin.

type Request

type Request struct {
	*http.Request
	Server     *Server           // Server.
	Cookie     *Cookie           // Cookie.
	Session    *gsession.Session // Session.
	Response   *Response         // Corresponding Response of this request.
	Router     *Router           // Matched Router for this request. Note that it's not available in HOOK handler.
	EnterTime  int64             // Request starting time in microseconds.
	LeaveTime  int64             // Request ending time in microseconds.
	Middleware *Middleware       // Middleware manager.
	StaticFile *StaticFile       // Static file object for static file serving.
	// contains filtered or unexported fields
}

Request is the context object for a request.

func (*Request) Assign added in v1.10.0

func (r *Request) Assign(key string, value interface{})

Assign binds a template variable to current request.

func (*Request) Assigns added in v1.10.0

func (r *Request) Assigns(data gview.Params)

Assigns binds multiple template variables to current request.

func (*Request) BasicAuth

func (r *Request) BasicAuth(user, pass string, tips ...string) bool

BasicAuth enables the http basic authentication feature with given passport and password and asks client for authentication. It returns true if authentication success, else returns false if failure.

func (*Request) Context added in v1.11.6

func (r *Request) Context() context.Context

Context retrieves and returns the request's context. This function overwrites the http.Request.Context function.

func (*Request) Exit

func (r *Request) Exit()

Exit exits executing of current HTTP handler.

func (*Request) ExitAll

func (r *Request) ExitAll()

ExitAll exits executing of current and following HTTP handlers.

func (*Request) ExitHook

func (r *Request) ExitHook()

ExitHook exits executing of current and following HTTP HOOK handlers.

func (*Request) Get

func (r *Request) Get(key string, def ...interface{}) interface{}

Get is alias of GetRequest, which is one of the most commonly used functions for retrieving parameter. See GetRequest.

func (*Request) GetArray

func (r *Request) GetArray(key string, def ...interface{}) []string

func (*Request) GetBody added in v1.10.0

func (r *Request) GetBody() []byte

GetRaw retrieves and returns request body content as bytes.

func (*Request) GetBodyString added in v1.10.0

func (r *Request) GetBodyString() string

GetRawString retrieves and returns request body content as string.

func (*Request) GetBool added in v1.9.2

func (r *Request) GetBool(key string, def ...interface{}) bool

func (*Request) GetClientIp

func (r *Request) GetClientIp() string

GetClientIp returns the client ip of this request without port.

func (*Request) GetCtx added in v1.12.0

func (r *Request) GetCtx() context.Context

GetCtx is alias for function Context. See Context.

func (*Request) GetCtxVar added in v1.12.0

func (r *Request) GetCtxVar(key interface{}, def ...interface{}) *gvar.Var

GetCtxVar retrieves and returns a Var with given key name.

func (*Request) GetError added in v1.10.0

func (r *Request) GetError() error

GetError returns the error occurs in the procedure of the request. It returns nil if there's no error.

func (*Request) GetFloat32

func (r *Request) GetFloat32(key string, def ...interface{}) float32

func (*Request) GetFloat64

func (r *Request) GetFloat64(key string, def ...interface{}) float64

func (*Request) GetFloats

func (r *Request) GetFloats(key string, def ...interface{}) []float64

func (*Request) GetForm added in v1.10.0

func (r *Request) GetForm(key string, def ...interface{}) interface{}

GetForm retrieves and returns parameter <key> from form. It returns <def> if <key> does not exist in the form. It returns nil if <def> is not passed.

func (*Request) GetFormArray added in v1.10.0

func (r *Request) GetFormArray(key string, def ...interface{}) []string

func (*Request) GetFormBool added in v1.10.0

func (r *Request) GetFormBool(key string, def ...interface{}) bool

func (*Request) GetFormFloat32 added in v1.10.0

func (r *Request) GetFormFloat32(key string, def ...interface{}) float32

func (*Request) GetFormFloat64 added in v1.10.0

func (r *Request) GetFormFloat64(key string, def ...interface{}) float64

func (*Request) GetFormFloats added in v1.10.0

func (r *Request) GetFormFloats(key string, def ...interface{}) []float64

func (*Request) GetFormInt added in v1.10.0

func (r *Request) GetFormInt(key string, def ...interface{}) int

func (*Request) GetFormInt32 added in v1.10.0

func (r *Request) GetFormInt32(key string, def ...interface{}) int32

func (*Request) GetFormInt64 added in v1.10.0

func (r *Request) GetFormInt64(key string, def ...interface{}) int64

func (*Request) GetFormInterfaces added in v1.10.0

func (r *Request) GetFormInterfaces(key string, def ...interface{}) []interface{}

func (*Request) GetFormInts added in v1.10.0

func (r *Request) GetFormInts(key string, def ...interface{}) []int

func (*Request) GetFormMap added in v1.10.0

func (r *Request) GetFormMap(kvMap ...map[string]interface{}) map[string]interface{}

GetFormMap retrieves and returns all form parameters passed from client as map. The parameter <kvMap> specifies the keys retrieving from client parameters, the associated values are the default values if the client does not pass.

func (*Request) GetFormMapStrStr added in v1.10.0

func (r *Request) GetFormMapStrStr(kvMap ...map[string]interface{}) map[string]string

GetFormMapStrStr retrieves and returns all form parameters passed from client as map[string]string. The parameter <kvMap> specifies the keys retrieving from client parameters, the associated values are the default values if the client does not pass.

func (*Request) GetFormMapStrVar added in v1.10.0

func (r *Request) GetFormMapStrVar(kvMap ...map[string]interface{}) map[string]*gvar.Var

GetFormMapStrVar retrieves and returns all form parameters passed from client as map[string]*gvar.Var. The parameter <kvMap> specifies the keys retrieving from client parameters, the associated values are the default values if the client does not pass.

func (*Request) GetFormString added in v1.10.0

func (r *Request) GetFormString(key string, def ...interface{}) string

func (*Request) GetFormStrings added in v1.10.0

func (r *Request) GetFormStrings(key string, def ...interface{}) []string

func (*Request) GetFormStruct added in v1.10.1

func (r *Request) GetFormStruct(pointer interface{}, mapping ...map[string]string) error

GetFormStruct retrieves all form parameters passed from client and converts them to given struct object. Note that the parameter <pointer> is a pointer to the struct object. The optional parameter <mapping> is used to specify the key to attribute mapping.

func (*Request) GetFormToStruct added in v1.10.0

func (r *Request) GetFormToStruct(pointer interface{}, mapping ...map[string]string) error

GetFormToStruct is alias of GetFormStruct. See GetFormStruct. Deprecated.

func (*Request) GetFormUint added in v1.10.0

func (r *Request) GetFormUint(key string, def ...interface{}) uint

func (*Request) GetFormUint32 added in v1.10.0

func (r *Request) GetFormUint32(key string, def ...interface{}) uint32

func (*Request) GetFormUint64 added in v1.10.0

func (r *Request) GetFormUint64(key string, def ...interface{}) uint64

func (*Request) GetFormVar added in v1.10.0

func (r *Request) GetFormVar(key string, def ...interface{}) *gvar.Var

func (*Request) GetHost

func (r *Request) GetHost() string

GetHost returns current request host name, which might be a domain or an IP without port.

func (*Request) GetInt

func (r *Request) GetInt(key string, def ...interface{}) int

func (*Request) GetInt32 added in v1.10.0

func (r *Request) GetInt32(key string, def ...interface{}) int32

func (*Request) GetInt64 added in v1.10.0

func (r *Request) GetInt64(key string, def ...interface{}) int64

func (*Request) GetInterfaces

func (r *Request) GetInterfaces(key string, def ...interface{}) []interface{}

func (*Request) GetInts

func (r *Request) GetInts(key string, def ...interface{}) []int

func (*Request) GetJson

func (r *Request) GetJson() (*gjson.Json, error)

GetJson parses current request content as JSON format, and returns the JSON object. Note that the request content is read from request BODY, not from any field of FORM.

func (*Request) GetMap

func (r *Request) GetMap(def ...map[string]interface{}) map[string]interface{}

func (*Request) GetMapStrStr added in v1.9.3

func (r *Request) GetMapStrStr(def ...map[string]interface{}) map[string]string

func (*Request) GetMultipartFiles added in v1.10.0

func (r *Request) GetMultipartFiles(name string) []*multipart.FileHeader

GetMultipartFiles returns the post files array. Note that the request form should be type of multipart.

func (*Request) GetMultipartForm added in v1.10.0

func (r *Request) GetMultipartForm() *multipart.Form

GetMultipartForm parses and returns the form as multipart form.

func (*Request) GetPage added in v1.11.6

func (r *Request) GetPage(totalSize, pageSize int) *gpage.Page

GetPage creates and returns the pagination object for given <totalSize> and <pageSize>. NOTE THAT the page parameter name from client is constantly defined as gpage.PAGE_NAME for simplification and convenience.

func (*Request) GetParam

func (r *Request) GetParam(key string, def ...interface{}) interface{}

GetParam returns custom parameter with given name <key>. It returns <def> if <key> does not exist. It returns nil if <def> is not passed.

func (*Request) GetParamVar added in v1.9.2

func (r *Request) GetParamVar(key string, def ...interface{}) *gvar.Var

GetParamVar returns custom parameter with given name <key> as *gvar.Var. It returns <def> if <key> does not exist. It returns nil if <def> is not passed.

func (*Request) GetPost

func (r *Request) GetPost(key string, def ...interface{}) interface{}

GetPost retrieves and returns parameter <key> from form and body. It returns <def> if <key> does not exist in neither form nor body. It returns nil if <def> is not passed.

Note that if there're multiple parameters with the same name, the parameters are retrieved and overwrote in order of priority: form > body.

Deprecated.

func (*Request) GetPostArray

func (r *Request) GetPostArray(key string, def ...interface{}) []string

Deprecated.

func (*Request) GetPostBool

func (r *Request) GetPostBool(key string, def ...interface{}) bool

Deprecated.

func (*Request) GetPostFloat32

func (r *Request) GetPostFloat32(key string, def ...interface{}) float32

Deprecated.

func (*Request) GetPostFloat64

func (r *Request) GetPostFloat64(key string, def ...interface{}) float64

Deprecated.

func (*Request) GetPostFloats

func (r *Request) GetPostFloats(key string, def ...interface{}) []float64

Deprecated.

func (*Request) GetPostInt

func (r *Request) GetPostInt(key string, def ...interface{}) int

Deprecated.

func (*Request) GetPostInt32 added in v1.9.8

func (r *Request) GetPostInt32(key string, def ...interface{}) int32

Deprecated.

func (*Request) GetPostInt64 added in v1.9.8

func (r *Request) GetPostInt64(key string, def ...interface{}) int64

Deprecated.

func (*Request) GetPostInterfaces

func (r *Request) GetPostInterfaces(key string, def ...interface{}) []interface{}

Deprecated.

func (*Request) GetPostInts

func (r *Request) GetPostInts(key string, def ...interface{}) []int

Deprecated.

func (*Request) GetPostMap

func (r *Request) GetPostMap(kvMap ...map[string]interface{}) map[string]interface{}

GetPostMap retrieves and returns all parameters in the form and body passed from client as map. The parameter <kvMap> specifies the keys retrieving from client parameters, the associated values are the default values if the client does not pass.

Note that if there're multiple parameters with the same name, the parameters are retrieved and overwrote in order of priority: form > body.

Deprecated.

func (*Request) GetPostMapStrStr added in v1.9.3

func (r *Request) GetPostMapStrStr(kvMap ...map[string]interface{}) map[string]string

GetPostMapStrStr retrieves and returns all parameters in the form and body passed from client as map[string]string. The parameter <kvMap> specifies the keys retrieving from client parameters, the associated values are the default values if the client does not pass.

Deprecated.

func (*Request) GetPostMapStrVar added in v1.9.3

func (r *Request) GetPostMapStrVar(kvMap ...map[string]interface{}) map[string]*gvar.Var

GetPostMapStrVar retrieves and returns all parameters in the form and body passed from client as map[string]*gvar.Var. The parameter <kvMap> specifies the keys retrieving from client parameters, the associated values are the default values if the client does not pass.

Deprecated.

func (*Request) GetPostString

func (r *Request) GetPostString(key string, def ...interface{}) string

Deprecated.

func (*Request) GetPostStrings

func (r *Request) GetPostStrings(key string, def ...interface{}) []string

Deprecated.

func (*Request) GetPostStruct added in v1.10.1

func (r *Request) GetPostStruct(pointer interface{}, mapping ...map[string]string) error

GetPostStruct retrieves all parameters in the form and body passed from client and converts them to given struct object. Note that the parameter <pointer> is a pointer to the struct object. The optional parameter <mapping> is used to specify the key to attribute mapping.

Deprecated.

func (*Request) GetPostToStruct

func (r *Request) GetPostToStruct(pointer interface{}, mapping ...map[string]string) error

GetPostToStruct is alias of GetQueryStruct. See GetPostStruct.

Deprecated.

func (*Request) GetPostUint

func (r *Request) GetPostUint(key string, def ...interface{}) uint

Deprecated.

func (*Request) GetPostUint32 added in v1.9.8

func (r *Request) GetPostUint32(key string, def ...interface{}) uint32

Deprecated.

func (*Request) GetPostUint64 added in v1.9.8

func (r *Request) GetPostUint64(key string, def ...interface{}) uint64

Deprecated.

func (*Request) GetPostVar

func (r *Request) GetPostVar(key string, def ...interface{}) *gvar.Var

Deprecated.

func (*Request) GetQuery

func (r *Request) GetQuery(key string, def ...interface{}) interface{}

GetQuery retrieves and returns parameter with given name <key> from query string and request body. It returns <def> if <key> does not exist in the query. It returns nil if <def> is not passed.

Note that if there're multiple parameters with the same name, the parameters are retrieved and overwrote in order of priority: query > body.

func (*Request) GetQueryArray

func (r *Request) GetQueryArray(key string, def ...interface{}) []string

func (*Request) GetQueryBool

func (r *Request) GetQueryBool(key string, def ...interface{}) bool

func (*Request) GetQueryFloat32

func (r *Request) GetQueryFloat32(key string, def ...interface{}) float32

func (*Request) GetQueryFloat64

func (r *Request) GetQueryFloat64(key string, def ...interface{}) float64

func (*Request) GetQueryFloats

func (r *Request) GetQueryFloats(key string, def ...interface{}) []float64

func (*Request) GetQueryInt

func (r *Request) GetQueryInt(key string, def ...interface{}) int

func (*Request) GetQueryInt32 added in v1.9.8

func (r *Request) GetQueryInt32(key string, def ...interface{}) int32

func (*Request) GetQueryInt64 added in v1.9.8

func (r *Request) GetQueryInt64(key string, def ...interface{}) int64

func (*Request) GetQueryInterfaces

func (r *Request) GetQueryInterfaces(key string, def ...interface{}) []interface{}

func (*Request) GetQueryInts

func (r *Request) GetQueryInts(key string, def ...interface{}) []int

func (*Request) GetQueryMap

func (r *Request) GetQueryMap(kvMap ...map[string]interface{}) map[string]interface{}

GetQueryMap retrieves and returns all parameters passed from client using HTTP GET method as map. The parameter <kvMap> specifies the keys retrieving from client parameters, the associated values are the default values if the client does not pass.

Note that if there're multiple parameters with the same name, the parameters are retrieved and overwrote in order of priority: query > body.

func (*Request) GetQueryMapStrStr added in v1.9.3

func (r *Request) GetQueryMapStrStr(kvMap ...map[string]interface{}) map[string]string

GetQueryMapStrStr retrieves and returns all parameters passed from client using HTTP GET method as map[string]string. The parameter <kvMap> specifies the keys retrieving from client parameters, the associated values are the default values if the client does not pass.

func (*Request) GetQueryMapStrVar added in v1.9.3

func (r *Request) GetQueryMapStrVar(kvMap ...map[string]interface{}) map[string]*gvar.Var

GetQueryMapStrVar retrieves and returns all parameters passed from client using HTTP GET method as map[string]*gvar.Var. The parameter <kvMap> specifies the keys retrieving from client parameters, the associated values are the default values if the client does not pass.

func (*Request) GetQueryString

func (r *Request) GetQueryString(key string, def ...interface{}) string

func (*Request) GetQueryStrings

func (r *Request) GetQueryStrings(key string, def ...interface{}) []string

func (*Request) GetQueryStruct added in v1.10.1

func (r *Request) GetQueryStruct(pointer interface{}, mapping ...map[string]string) error

GetQueryStruct retrieves all parameters passed from client using HTTP GET method and converts them to given struct object. Note that the parameter <pointer> is a pointer to the struct object. The optional parameter <mapping> is used to specify the key to attribute mapping.

func (*Request) GetQueryToStruct

func (r *Request) GetQueryToStruct(pointer interface{}, mapping ...map[string]string) error

GetQueryToStruct is alias of GetQueryStruct. See GetQueryStruct. Deprecated.

func (*Request) GetQueryUint

func (r *Request) GetQueryUint(key string, def ...interface{}) uint

func (*Request) GetQueryUint32 added in v1.9.8

func (r *Request) GetQueryUint32(key string, def ...interface{}) uint32

func (*Request) GetQueryUint64 added in v1.9.8

func (r *Request) GetQueryUint64(key string, def ...interface{}) uint64

func (*Request) GetQueryVar

func (r *Request) GetQueryVar(key string, def ...interface{}) *gvar.Var

func (*Request) GetRaw

func (r *Request) GetRaw() []byte

GetRaw is alias of GetBody. See GetBody.

func (*Request) GetRawString

func (r *Request) GetRawString() string

GetRawString is alias of GetBodyString. See GetBodyString.

func (*Request) GetReferer

func (r *Request) GetReferer() string

GetReferer returns referer of this request.

func (*Request) GetRequest

func (r *Request) GetRequest(key string, def ...interface{}) interface{}

GetRequest retrieves and returns the parameter named <key> passed from client and custom params as interface{}, no matter what HTTP method the client is using. The parameter <def> specifies the default value if the <key> does not exist.

GetRequest is one of the most commonly used functions for retrieving parameters.

Note that if there're multiple parameters with the same name, the parameters are retrieved and overwrote in order of priority: router < query < body < form < custom.

func (*Request) GetRequestArray

func (r *Request) GetRequestArray(key string, def ...interface{}) []string

GetRequestArray retrieves and returns the parameter named <key> passed from client and custom params as []string, no matter what HTTP method the client is using. The parameter <def> specifies the default value if the <key> does not exist.

func (*Request) GetRequestBool

func (r *Request) GetRequestBool(key string, def ...interface{}) bool

GetRequestBool retrieves and returns the parameter named <key> passed from client and custom params as bool, no matter what HTTP method the client is using. The parameter <def> specifies the default value if the <key> does not exist.

func (*Request) GetRequestFloat32

func (r *Request) GetRequestFloat32(key string, def ...interface{}) float32

GetRequestFloat32 retrieves and returns the parameter named <key> passed from client and custom params as float32, no matter what HTTP method the client is using. The parameter <def> specifies the default value if the <key> does not exist.

func (*Request) GetRequestFloat64

func (r *Request) GetRequestFloat64(key string, def ...interface{}) float64

GetRequestFloat64 retrieves and returns the parameter named <key> passed from client and custom params as float64, no matter what HTTP method the client is using. The parameter <def> specifies the default value if the <key> does not exist.

func (*Request) GetRequestFloats

func (r *Request) GetRequestFloats(key string, def ...interface{}) []float64

GetRequestFloats retrieves and returns the parameter named <key> passed from client and custom params as []float64, no matter what HTTP method the client is using. The parameter <def> specifies the default value if the <key> does not exist.

func (*Request) GetRequestInt

func (r *Request) GetRequestInt(key string, def ...interface{}) int

GetRequestInt retrieves and returns the parameter named <key> passed from client and custom params as int, no matter what HTTP method the client is using. The parameter <def> specifies the default value if the <key> does not exist.

func (*Request) GetRequestInt32 added in v1.9.8

func (r *Request) GetRequestInt32(key string, def ...interface{}) int32

GetRequestInt32 retrieves and returns the parameter named <key> passed from client and custom params as int32, no matter what HTTP method the client is using. The parameter <def> specifies the default value if the <key> does not exist.

func (*Request) GetRequestInt64 added in v1.9.8

func (r *Request) GetRequestInt64(key string, def ...interface{}) int64

GetRequestInt64 retrieves and returns the parameter named <key> passed from client and custom params as int64, no matter what HTTP method the client is using. The parameter <def> specifies the default value if the <key> does not exist.

func (*Request) GetRequestInterfaces

func (r *Request) GetRequestInterfaces(key string, def ...interface{}) []interface{}

GetRequestInterfaces retrieves and returns the parameter named <key> passed from client and custom params as []interface{}, no matter what HTTP method the client is using. The parameter <def> specifies the default value if the <key> does not exist.

func (*Request) GetRequestInts

func (r *Request) GetRequestInts(key string, def ...interface{}) []int

GetRequestInts retrieves and returns the parameter named <key> passed from client and custom params as []int, no matter what HTTP method the client is using. The parameter <def> specifies the default value if the <key> does not exist.

func (*Request) GetRequestMap

func (r *Request) GetRequestMap(kvMap ...map[string]interface{}) map[string]interface{}

GetRequestMap retrieves and returns all parameters passed from client and custom params as map, no matter what HTTP method the client is using. The parameter <kvMap> specifies the keys retrieving from client parameters, the associated values are the default values if the client does not pass the according keys.

GetRequestMap is one of the most commonly used functions for retrieving parameters.

Note that if there're multiple parameters with the same name, the parameters are retrieved and overwrote in order of priority: router < query < body < form < custom.

func (*Request) GetRequestMapStrStr added in v1.9.3

func (r *Request) GetRequestMapStrStr(kvMap ...map[string]interface{}) map[string]string

GetRequestMapStrStr retrieves and returns all parameters passed from client and custom params as map[string]string, no matter what HTTP method the client is using. The parameter <kvMap> specifies the keys retrieving from client parameters, the associated values are the default values if the client does not pass.

func (*Request) GetRequestMapStrVar added in v1.9.3

func (r *Request) GetRequestMapStrVar(kvMap ...map[string]interface{}) map[string]*gvar.Var

GetRequestMapStrVar retrieves and returns all parameters passed from client and custom params as map[string]*gvar.Var, no matter what HTTP method the client is using. The parameter <kvMap> specifies the keys retrieving from client parameters, the associated values are the default values if the client does not pass.

func (*Request) GetRequestString

func (r *Request) GetRequestString(key string, def ...interface{}) string

GetRequestString retrieves and returns the parameter named <key> passed from client and custom params as string, no matter what HTTP method the client is using. The parameter <def> specifies the default value if the <key> does not exist.

func (*Request) GetRequestStrings

func (r *Request) GetRequestStrings(key string, def ...interface{}) []string

GetRequestStrings retrieves and returns the parameter named <key> passed from client and custom params as []string, no matter what HTTP method the client is using. The parameter <def> specifies the default value if the <key> does not exist.

func (*Request) GetRequestStruct added in v1.10.1

func (r *Request) GetRequestStruct(pointer interface{}, mapping ...map[string]string) error

GetRequestStruct retrieves all parameters passed from client and custom params no matter what HTTP method the client is using, and converts them to given struct object. Note that the parameter <pointer> is a pointer to the struct object. The optional parameter <mapping> is used to specify the key to attribute mapping.

func (*Request) GetRequestToStruct

func (r *Request) GetRequestToStruct(pointer interface{}, mapping ...map[string]string) error

GetRequestToStruct is alias of GetRequestStruct. See GetRequestStruct. Deprecated.

func (*Request) GetRequestUint

func (r *Request) GetRequestUint(key string, def ...interface{}) uint

GetRequestUint retrieves and returns the parameter named <key> passed from client and custom params as uint, no matter what HTTP method the client is using. The parameter <def> specifies the default value if the <key> does not exist.

func (*Request) GetRequestUint32 added in v1.9.8

func (r *Request) GetRequestUint32(key string, def ...interface{}) uint32

GetRequestUint32 retrieves and returns the parameter named <key> passed from client and custom params as uint32, no matter what HTTP method the client is using. The parameter <def> specifies the default value if the <key> does not exist.

func (*Request) GetRequestUint64 added in v1.9.8

func (r *Request) GetRequestUint64(key string, def ...interface{}) uint64

GetRequestUint64 retrieves and returns the parameter named <key> passed from client and custom params as uint64, no matter what HTTP method the client is using. The parameter <def> specifies the default value if the <key> does not exist.

func (*Request) GetRequestVar

func (r *Request) GetRequestVar(key string, def ...interface{}) *gvar.Var

GetRequestVar retrieves and returns the parameter named <key> passed from client and custom params as *gvar.Var, no matter what HTTP method the client is using. The parameter <def> specifies the default value if the <key> does not exist.

func (*Request) GetRouterString

func (r *Request) GetRouterString(key string, def ...interface{}) string

GetRouterString retrieves and returns the router value as string with given key name <key>. It returns <def> if <key> does not exist.

func (*Request) GetRouterValue added in v1.9.2

func (r *Request) GetRouterValue(key string, def ...interface{}) interface{}

GetRouterValue retrieves and returns the router value with given key name <key>. It returns <def> if <key> does not exist.

func (*Request) GetRouterVar added in v1.9.2

func (r *Request) GetRouterVar(key string, def ...interface{}) *gvar.Var

GetRouterVar retrieves and returns the router value as *gvar.var with given key name <key>. It returns <def> if <key> does not exist.

func (*Request) GetSessionId

func (r *Request) GetSessionId() string

GetSessionId retrieves and returns session id from cookie or header.

func (*Request) GetString

func (r *Request) GetString(key string, def ...interface{}) string

func (*Request) GetStrings

func (r *Request) GetStrings(key string, def ...interface{}) []string

func (*Request) GetStruct added in v1.10.1

func (r *Request) GetStruct(pointer interface{}, mapping ...map[string]string) error

GetStruct is alias of GetRequestToStruct. See GetRequestToStruct.

func (*Request) GetToStruct

func (r *Request) GetToStruct(pointer interface{}, mapping ...map[string]string) error

GetToStruct is alias of GetRequestToStruct. See GetRequestToStruct. Deprecated.

func (*Request) GetUint

func (r *Request) GetUint(key string, def ...interface{}) uint

func (*Request) GetUint32 added in v1.10.0

func (r *Request) GetUint32(key string, def ...interface{}) uint32

func (*Request) GetUint64 added in v1.10.0

func (r *Request) GetUint64(key string, def ...interface{}) uint64

func (*Request) GetUploadFile added in v1.11.5

func (r *Request) GetUploadFile(name string) *UploadFile

GetUploadFile retrieves and returns the uploading file with specified form name. This function is used for retrieving single uploading file object, which is uploaded using multipart form content type.

Note that the <name> is the file field name of the multipart form from client.

func (*Request) GetUploadFiles added in v1.11.5

func (r *Request) GetUploadFiles(name string) UploadFiles

GetUploadFiles retrieves and returns multiple uploading files with specified form name. This function is used for retrieving multiple uploading file objects, which are uploaded using multipart form content type.

Note that the <name> is the file field name of the multipart form from client.

func (*Request) GetUrl

func (r *Request) GetUrl() string

GetUrl returns current URL of this request.

func (*Request) GetVar

func (r *Request) GetVar(key string, def ...interface{}) *gvar.Var

GetVar is alis of GetRequestVar. See GetRequestVar.

func (*Request) GetView added in v1.10.0

func (r *Request) GetView() *gview.View

GetView returns the template view engine object for this request.

func (*Request) IsAjaxRequest

func (r *Request) IsAjaxRequest() bool

IsAjaxRequest checks and returns whether current request is an AJAX request.

func (*Request) IsExited

func (r *Request) IsExited() bool

IsExited checks and returns whether current request is exited.

func (*Request) IsFileRequest

func (r *Request) IsFileRequest() bool

IsFileRequest checks and returns whether current request is serving file.

func (*Request) Parse added in v1.11.0

func (r *Request) Parse(pointer interface{}) error

Parse calls r.GetStruct to convert the parameters, which are sent from client, to given struct, and then calls gvalid.CheckStruct validating the struct according to the validation tag of the struct.

See GetStruct, gvalid.CheckStruct.

func (*Request) RefillBody added in v1.11.5

func (r *Request) RefillBody()

RefillBody refills the request body object after read all of its content. It makes the request body reusable for next reading.

func (*Request) SetCtxVar added in v1.12.0

func (r *Request) SetCtxVar(key interface{}, value interface{})

SetCtxVar sets custom parameter to context with key-value pair.

func (*Request) SetForm added in v1.10.0

func (r *Request) SetForm(key string, value interface{})

SetForm sets custom form value with key-value pair.

func (*Request) SetParam

func (r *Request) SetParam(key string, value interface{})

SetParam sets custom parameter with key-value pair.

func (*Request) SetQuery

func (r *Request) SetQuery(key string, value interface{})

SetQuery sets custom query value with key-value pair.

func (*Request) SetView added in v1.10.0

func (r *Request) SetView(view *gview.View)

SetView sets template view engine object for this request.

func (*Request) WebSocket

func (r *Request) WebSocket() (*WebSocket, error)

WebSocket upgrades current request as a websocket request. It returns a new WebSocket object if success, or the error if failure. Note that the request should be a websocket request, or it will surely fail upgrading.

type Response

type Response struct {
	*ResponseWriter                 // Underlying ResponseWriter.
	Server          *Server         // Parent server.
	Writer          *ResponseWriter // Alias of ResponseWriter.
	Request         *Request        // According request.
}

Response is the http response manager. Note that it implements the http.ResponseWriter interface with buffering feature.

func (*Response) Buffer

func (r *Response) Buffer() []byte

BufferString returns the buffered content as []byte.

func (*Response) BufferLength

func (r *Response) BufferLength() int

BufferLength returns the length of the buffered content.

func (*Response) BufferString added in v1.9.3

func (r *Response) BufferString() string

BufferString returns the buffered content as string.

func (*Response) CORS

func (r *Response) CORS(options CORSOptions)

CORS sets custom CORS options. See https://www.w3.org/TR/cors/ .

func (*Response) CORSAllowedOrigin added in v1.9.3

func (r *Response) CORSAllowedOrigin(options CORSOptions) bool

CORSAllowed checks whether the current request origin is allowed cross-domain.

func (*Response) CORSDefault

func (r *Response) CORSDefault()

CORSDefault sets CORS with default CORS options, which allows any cross-domain request.

func (*Response) ClearBuffer

func (r *Response) ClearBuffer()

ClearBuffer clears the response buffer.

func (*Response) DefaultCORSOptions

func (r *Response) DefaultCORSOptions() CORSOptions

DefaultCORSOptions returns the default CORS options, which allows any cross-domain request.

func (*Response) Output

func (r *Response) Output()

Output outputs the buffer content to the client and clears the buffer.

func (*Response) ParseTpl

func (r *Response) ParseTpl(tpl string, params ...gview.Params) (string, error)

ParseTpl parses given template file <tpl> with given template variables <params> and returns the parsed template content.

func (*Response) ParseTplContent

func (r *Response) ParseTplContent(content string, params ...gview.Params) (string, error)

ParseTplContent parses given template file <file> with given template parameters <params> and returns the parsed template content.

func (*Response) ParseTplDefault added in v1.10.0

func (r *Response) ParseTplDefault(params ...gview.Params) (string, error)

ParseDefault parses the default template file with params.

func (*Response) RedirectBack

func (r *Response) RedirectBack(code ...int)

RedirectBack redirects client back to referer. The optional parameter <code> specifies the http status code for redirecting, which commonly can be 301 or 302. It's 302 in default.

func (*Response) RedirectTo

func (r *Response) RedirectTo(location string, code ...int)

RedirectTo redirects client to another location. The optional parameter <code> specifies the http status code for redirecting, which commonly can be 301 or 302. It's 302 in default.

func (*Response) ServeFile

func (r *Response) ServeFile(path string, allowIndex ...bool)

ServeFile serves the file to the response.

func (*Response) ServeFileDownload

func (r *Response) ServeFileDownload(path string, name ...string)

ServeFileDownload serves file downloading to the response.

func (*Response) SetBuffer

func (r *Response) SetBuffer(data []byte)

SetBuffer overwrites the buffer with <data>.

func (*Response) Write

func (r *Response) Write(content ...interface{})

Write writes <content> to the response buffer.

func (*Response) WriteExit added in v1.10.0

func (r *Response) WriteExit(content ...interface{})

WriteExit writes <content> to the response buffer and exits executing of current handler. The "Exit" feature is commonly used to replace usage of return statement in the handler, for convenience.

func (*Response) WriteJson

func (r *Response) WriteJson(content interface{}) error

WriteJson writes <content> to the response with JSON format.

func (*Response) WriteJsonExit added in v1.10.0

func (r *Response) WriteJsonExit(content interface{}) error

WriteJsonExit writes <content> to the response with JSON format and exits executing of current handler if success. The "Exit" feature is commonly used to replace usage of return statement in the handler, for convenience.

func (*Response) WriteJsonP

func (r *Response) WriteJsonP(content interface{}) error

WriteJson writes <content> to the response with JSONP format.

Note that there should be a "callback" parameter in the request for JSONP format.

func (*Response) WriteJsonPExit added in v1.10.0

func (r *Response) WriteJsonPExit(content interface{}) error

WriteJsonPExit writes <content> to the response with JSONP format and exits executing of current handler if success. The "Exit" feature is commonly used to replace usage of return statement in the handler, for convenience.

Note that there should be a "callback" parameter in the request for JSONP format.

func (*Response) WriteOver added in v1.9.8

func (r *Response) WriteOver(content ...interface{})

WriteOver overwrites the response buffer with <content>.

func (*Response) WriteOverExit added in v1.10.0

func (r *Response) WriteOverExit(content ...interface{})

WriteOverExit overwrites the response buffer with <content> and exits executing of current handler. The "Exit" feature is commonly used to replace usage of return statement in the handler, for convenience.

func (*Response) WriteStatus

func (r *Response) WriteStatus(status int, content ...interface{})

WriteStatus writes HTTP <status> and <content> to the response.

func (*Response) WriteStatusExit added in v1.10.0

func (r *Response) WriteStatusExit(status int, content ...interface{})

WriteStatusExit writes HTTP <status> and <content> to the response and exits executing of current handler if success. The "Exit" feature is commonly used to replace usage of return statement in the handler, for convenience.

func (*Response) WriteTpl

func (r *Response) WriteTpl(tpl string, params ...gview.Params) error

WriteTpl parses and responses given template file. The parameter <params> specifies the template variables for parsing.

func (*Response) WriteTplContent

func (r *Response) WriteTplContent(content string, params ...gview.Params) error

WriteTplContent parses and responses the template content. The parameter <params> specifies the template variables for parsing.

func (*Response) WriteTplDefault added in v1.10.0

func (r *Response) WriteTplDefault(params ...gview.Params) error

WriteTplDefault parses and responses the default template file. The parameter <params> specifies the template variables for parsing.

func (*Response) WriteXml

func (r *Response) WriteXml(content interface{}, rootTag ...string) error

WriteXml writes <content> to the response with XML format.

func (*Response) WriteXmlExit added in v1.10.0

func (r *Response) WriteXmlExit(content interface{}, rootTag ...string) error

WriteXmlExit writes <content> to the response with XML format and exits executing of current handler if success. The "Exit" feature is commonly used to replace usage of return statement in the handler, for convenience.

func (*Response) Writef

func (r *Response) Writef(format string, params ...interface{})

Writef writes the response with fmt.Sprintf.

func (*Response) WritefExit added in v1.10.0

func (r *Response) WritefExit(format string, params ...interface{})

WritefExit writes the response with fmt.Sprintf and exits executing of current handler. The "Exit" feature is commonly used to replace usage of return statement in the handler, for convenience.

func (*Response) Writefln

func (r *Response) Writefln(format string, params ...interface{})

Writefln writes the response with fmt.Sprintf and new line.

func (*Response) WriteflnExit added in v1.10.0

func (r *Response) WriteflnExit(format string, params ...interface{})

WriteflnExit writes the response with fmt.Sprintf and new line and exits executing of current handler. The "Exit" feature is commonly used to replace usage of return statement in the handler, for convenience.

func (*Response) Writeln

func (r *Response) Writeln(content ...interface{})

Writef writes the response with <content> and new line.

func (*Response) WritelnExit added in v1.10.0

func (r *Response) WritelnExit(content ...interface{})

WritelnExit writes the response with <content> and new line and exits executing of current handler. The "Exit" feature is commonly used to replace usage of return statement in the handler, for convenience.

type ResponseWriter

type ResponseWriter struct {
	Status int // HTTP status.
	// contains filtered or unexported fields
}

ResponseWriter is the custom writer for http response.

func (*ResponseWriter) Header added in v1.9.4

func (w *ResponseWriter) Header() http.Header

Header implements the interface function of http.ResponseWriter.Header.

func (*ResponseWriter) Hijack added in v1.9.4

func (w *ResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error)

Hijack implements the interface function of http.Hijacker.Hijack.

func (*ResponseWriter) OutputBuffer

func (w *ResponseWriter) OutputBuffer()

OutputBuffer outputs the buffer to client and clears the buffer.

func (*ResponseWriter) RawWriter added in v1.9.8

func (w *ResponseWriter) RawWriter() http.ResponseWriter

RawWriter returns the underlying ResponseWriter.

func (*ResponseWriter) Write

func (w *ResponseWriter) Write(data []byte) (int, error)

Write implements the interface function of http.ResponseWriter.Write.

func (*ResponseWriter) WriteHeader

func (w *ResponseWriter) WriteHeader(status int)

WriteHeader implements the interface of http.ResponseWriter.WriteHeader.

type Router

type Router struct {
	Uri      string   // URI.
	Method   string   // HTTP method
	Domain   string   // Bound domain.
	RegRule  string   // Parsed regular expression for route matching.
	RegNames []string // Parsed router parameter names.
	Priority int      // Just for reference.
}

Router object.

type RouterGroup

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

RouterGroup is a group wrapping multiple routes and middleware.

func (*RouterGroup) ALL

func (g *RouterGroup) ALL(pattern string, object interface{}, params ...interface{}) *RouterGroup

ALL registers a http handler to given route pattern and all http methods.

func (*RouterGroup) Bind

func (g *RouterGroup) Bind(items []GroupItem) *RouterGroup

Bind does batch route registering feature for router group.

func (*RouterGroup) CONNECT

func (g *RouterGroup) CONNECT(pattern string, object interface{}, params ...interface{}) *RouterGroup

CONNECT registers a http handler to given route pattern and http method: CONNECT.

func (*RouterGroup) Clone

func (g *RouterGroup) Clone() *RouterGroup

Clone returns a new router group which is a clone of current group.

func (*RouterGroup) DELETE

func (g *RouterGroup) DELETE(pattern string, object interface{}, params ...interface{}) *RouterGroup

DELETE registers a http handler to given route pattern and http method: DELETE.

func (*RouterGroup) GET

func (g *RouterGroup) GET(pattern string, object interface{}, params ...interface{}) *RouterGroup

GET registers a http handler to given route pattern and http method: GET.

func (*RouterGroup) Group

func (g *RouterGroup) Group(prefix string, groups ...func(group *RouterGroup)) *RouterGroup

Group creates and returns a sub-group of current router group.

func (*RouterGroup) HEAD

func (g *RouterGroup) HEAD(pattern string, object interface{}, params ...interface{}) *RouterGroup

HEAD registers a http handler to given route pattern and http method: HEAD.

func (*RouterGroup) Hook

func (g *RouterGroup) Hook(pattern string, hook string, handler HandlerFunc) *RouterGroup

Hook registers a hook to given route pattern.

func (*RouterGroup) Middleware

func (g *RouterGroup) Middleware(handlers ...HandlerFunc) *RouterGroup

Middleware binds one or more middleware to the router group.

func (*RouterGroup) OPTIONS

func (g *RouterGroup) OPTIONS(pattern string, object interface{}, params ...interface{}) *RouterGroup

OPTIONS registers a http handler to given route pattern and http method: OPTIONS.

func (*RouterGroup) PATCH

func (g *RouterGroup) PATCH(pattern string, object interface{}, params ...interface{}) *RouterGroup

PATCH registers a http handler to given route pattern and http method: PATCH.

func (*RouterGroup) POST

func (g *RouterGroup) POST(pattern string, object interface{}, params ...interface{}) *RouterGroup

POST registers a http handler to given route pattern and http method: POST.

func (*RouterGroup) PUT

func (g *RouterGroup) PUT(pattern string, object interface{}, params ...interface{}) *RouterGroup

PUT registers a http handler to given route pattern and http method: PUT.

func (*RouterGroup) REST

func (g *RouterGroup) REST(pattern string, object interface{}) *RouterGroup

REST registers a http handler to given route pattern according to REST rule.

func (*RouterGroup) TRACE

func (g *RouterGroup) TRACE(pattern string, object interface{}, params ...interface{}) *RouterGroup

TRACE registers a http handler to given route pattern and http method: TRACE.

type RouterItem added in v1.10.0

type RouterItem struct {
	Server           string // Server name.
	Address          string // Listening address.
	Domain           string // Bound domain.
	Type             int    // Router type.
	Middleware       string // Bound middleware.
	Method           string // Handler method name.
	Route            string // Route URI.
	Priority         int    // Just for reference.
	IsServiceHandler bool   // Is service handler.
	// contains filtered or unexported fields
}

Router item just for route dumps.

type Server

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

Server wraps the http.Server and provides more feature.

func GetServer

func GetServer(name ...interface{}) *Server

获取/创建一个默认配置的HTTP Server(默认监听端口是80) 单例模式,请保证name的唯一性

func (*Server) AddSearchPath

func (s *Server) AddSearchPath(path string)

AddSearchPath add searching directory path for static file service.

func (*Server) AddStaticPath

func (s *Server) AddStaticPath(prefix string, path string)

AddStaticPath sets the uri to static directory path mapping for static file service.

func (*Server) BindController

func (s *Server) BindController(pattern string, controller Controller, method ...string)

绑定控制器,控制器需要实现 gmvc.Controller 接口, 这种方式绑定的控制器每一次请求都会初始化一个新的控制器对象进行处理,对应不同的请求会话, 第三个参数methods用以指定需要注册的方法,支持多个方法名称,多个方法以英文“,”号分隔,区分大小写.

func (*Server) BindControllerMethod

func (s *Server) BindControllerMethod(pattern string, controller Controller, method string)

绑定路由到指定的方法执行, 第三个参数method仅支持一个方法注册,不支持多个,并且区分大小写。

func (*Server) BindControllerRest

func (s *Server) BindControllerRest(pattern string, controller Controller)

绑定控制器(RESTFul),控制器需要实现gmvc.Controller接口 方法会识别HTTP方法,并做REST绑定处理,例如:Post方法会绑定到HTTP POST的方法请求处理,Delete方法会绑定到HTTP DELETE的方法请求处理 因此只会绑定HTTP Method对应的方法,其他方法不会自动注册绑定 这种方式绑定的控制器每一次请求都会初始化一个新的控制器对象进行处理,对应不同的请求会话

func (*Server) BindHandler

func (s *Server) BindHandler(pattern string, handler HandlerFunc)

注意该方法是直接绑定函数的内存地址,执行的时候直接执行该方法,不会存在初始化新的控制器逻辑

func (*Server) BindHookHandler

func (s *Server) BindHookHandler(pattern string, hook string, handler HandlerFunc)

绑定指定的hook回调函数, pattern参数同BindHandler,支持命名路由;hook参数的值由ghttp server设定,参数不区分大小写

func (*Server) BindHookHandlerByMap

func (s *Server) BindHookHandlerByMap(pattern string, hookMap map[string]HandlerFunc)

通过map批量绑定回调函数

func (*Server) BindMiddleware

func (s *Server) BindMiddleware(pattern string, handlers ...HandlerFunc)

BindMiddleware registers one or more global middleware to the server. Global middleware can be used standalone without service handler, which intercepts all dynamic requests before or after service handler. The parameter <pattern> specifies what route pattern the middleware intercepts, which is usually a "fuzzy" pattern like "/:name", "/*any" or "/{field}".

func (*Server) BindMiddlewareDefault added in v1.9.2

func (s *Server) BindMiddlewareDefault(handlers ...HandlerFunc)

BindMiddlewareDefault registers one or more global middleware to the server using default pattern "/*". Global middleware can be used standalone without service handler, which intercepts all dynamic requests before or after service handler.

func (*Server) BindObject

func (s *Server) BindObject(pattern string, object interface{}, method ...string)

绑定对象到URI请求处理中,会自动识别方法名称,并附加到对应的URI地址后面 第三个参数methods用以指定需要注册的方法,支持多个方法名称,多个方法以英文“,”号分隔,区分大小写

func (*Server) BindObjectMethod

func (s *Server) BindObjectMethod(pattern string, object interface{}, method string)

绑定对象到URI请求处理中,会自动识别方法名称,并附加到对应的URI地址后面, 第三个参数method仅支持一个方法注册,不支持多个,并且区分大小写。

func (*Server) BindObjectRest

func (s *Server) BindObjectRest(pattern string, object interface{})

绑定对象到URI请求处理中,会自动识别方法名称,并附加到对应的URI地址后面, 需要注意对象方法的定义必须按照 ghttp.HandlerFunc 来定义

func (*Server) BindStatusHandler

func (s *Server) BindStatusHandler(status int, handler HandlerFunc)

绑定指定的状态码回调函数

func (*Server) BindStatusHandlerByMap

func (s *Server) BindStatusHandlerByMap(handlerMap map[int]HandlerFunc)

通过map批量绑定状态码回调函数

func (*Server) Domain

func (s *Server) Domain(domains string) *Domain

生成一个域名对象, 参数 domains 支持给定多个域名。

func (*Server) EnableAdmin

func (s *Server) EnableAdmin(pattern ...string)

开启服务管理支持

func (*Server) EnableHTTPS

func (s *Server) EnableHTTPS(certFile, keyFile string, tlsConfig ...*tls.Config)

EnableHTTPS enables HTTPS with given certification and key files for the server. The optional parameter <tlsConfig> specifies custom TLS configuration.

func (*Server) EnablePProf added in v1.10.0

func (s *Server) EnablePProf(pattern ...string)

EnablePProf enables PProf feature for server.

func (*Server) GetCookieDomain

func (s *Server) GetCookieDomain() string

func (*Server) GetCookieMaxAge

func (s *Server) GetCookieMaxAge() time.Duration

func (*Server) GetCookiePath

func (s *Server) GetCookiePath() string

func (*Server) GetIndexFiles added in v1.11.3

func (s *Server) GetIndexFiles() []string

GetIndexFiles retrieves and returns the index files from server.

func (*Server) GetLogPath

func (s *Server) GetLogPath() string

获取日志目录

func (*Server) GetName

func (s *Server) GetName() string

GetName returns the name of the server.

func (*Server) GetRouterArray added in v1.10.1

func (s *Server) GetRouterArray() []RouterItem

GetRouterArray retrieves and returns the router array. The key of the returned map is the domain of the server.

func (*Server) GetSessionIdName

func (s *Server) GetSessionIdName() string

func (*Server) GetSessionMaxAge

func (s *Server) GetSessionMaxAge() time.Duration

func (*Server) Group

func (s *Server) Group(prefix string, groups ...func(group *RouterGroup)) *RouterGroup

Group creates and returns a RouterGroup object.

func (*Server) Handler added in v1.10.0

func (s *Server) Handler() http.Handler

Handler returns the request handler of the server.

func (*Server) IsAccessLogEnabled

func (s *Server) IsAccessLogEnabled() bool

access log日志功能是否开启

func (*Server) IsErrorLogEnabled

func (s *Server) IsErrorLogEnabled() bool

error log日志功能是否开启

func (*Server) Logger added in v1.11.5

func (s *Server) Logger() *glog.Logger

Logger returns the logger of the server.

func (*Server) Plugin added in v1.11.4

func (s *Server) Plugin(plugin ...Plugin)

Plugin adds plugin to server.

func (*Server) Run

func (s *Server) Run()

Run starts server listening in blocking way. It's commonly used for single server situation.

func (*Server) SetAccessLogEnabled

func (s *Server) SetAccessLogEnabled(enabled bool)

设置是否开启access log日志功能

func (*Server) SetAddr

func (s *Server) SetAddr(address string)

SetAddr sets the listening address for the server. The address is like ':80', '0.0.0.0:80', '127.0.0.1:80', '180.18.99.10:80', etc.

func (*Server) SetConfig

func (s *Server) SetConfig(c ServerConfig) error

SetConfig sets the configuration for the server.

func (*Server) SetConfigWithMap

func (s *Server) SetConfigWithMap(m map[string]interface{}) error

SetConfigWithMap sets the configuration for the server using map.

func (*Server) SetCookieDomain

func (s *Server) SetCookieDomain(domain string)

func (*Server) SetCookieMaxAge

func (s *Server) SetCookieMaxAge(ttl time.Duration)

func (*Server) SetCookiePath

func (s *Server) SetCookiePath(path string)

func (*Server) SetDumpRouterMap added in v1.10.0

func (s *Server) SetDumpRouterMap(enabled bool)

func (*Server) SetErrorLogEnabled

func (s *Server) SetErrorLogEnabled(enabled bool)

设置是否开启error log日志功能

func (*Server) SetErrorStack

func (s *Server) SetErrorStack(enabled bool)

设置是否开启error stack打印功能

func (*Server) SetFileServerEnabled

func (s *Server) SetFileServerEnabled(enabled bool)

SetFileServerEnabled enables/disables the static file service. It's the main switch for the static file service. When static file service configuration functions like SetServerRoot, AddSearchPath and AddStaticPath are called, this configuration is automatically enabled.

func (*Server) SetFormParsingMemory added in v1.9.2

func (s *Server) SetFormParsingMemory(maxMemory int64)

func (*Server) SetHTTPSAddr

func (s *Server) SetHTTPSAddr(address string)

SetHTTPSAddr sets the HTTPS listening ports for the server.

func (*Server) SetHTTPSPort

func (s *Server) SetHTTPSPort(port ...int)

SetHTTPSPort sets the HTTPS listening ports for the server. The listening ports can be multiple.

func (*Server) SetIdleTimeout

func (s *Server) SetIdleTimeout(t time.Duration)

SetIdleTimeout sets the IdleTimeout for the server.

func (*Server) SetIndexFiles

func (s *Server) SetIndexFiles(indexFiles []string)

SetIndexFiles sets the index files for server.

func (*Server) SetIndexFolder

func (s *Server) SetIndexFolder(enabled bool)

SetIndexFolder enables/disables listing the sub-files if requesting a directory.

func (*Server) SetKeepAlive

func (s *Server) SetKeepAlive(enabled bool)

SetKeepAlive sets the KeepAlive for the server.

func (*Server) SetLogPath

func (s *Server) SetLogPath(path string)

设置日志目录,只有在设置了日志目录的情况下才会输出日志到日志文件中。

func (*Server) SetLogStdout

func (s *Server) SetLogStdout(enabled bool)

设置日志内容是否输出到终端,默认情况下只有错误日志才会自动输出到终端。 如果需要输出请求日志到终端,默认情况下使用SetAccessLogEnabled方法开启请求日志特性即可。

func (*Server) SetMaxHeaderBytes

func (s *Server) SetMaxHeaderBytes(b int)

SetMaxHeaderBytes sets the MaxHeaderBytes for the server.

func (*Server) SetNameToUriType

func (s *Server) SetNameToUriType(t int)

func (*Server) SetPort

func (s *Server) SetPort(port ...int)

SetPort sets the listening ports for the server. The listening ports can be multiple.

func (*Server) SetReadTimeout

func (s *Server) SetReadTimeout(t time.Duration)

SetReadTimeout sets the ReadTimeout for the server.

func (*Server) SetRewrite

func (s *Server) SetRewrite(uri string, rewrite string)

func (*Server) SetRewriteMap

func (s *Server) SetRewriteMap(rewrites map[string]string)

func (*Server) SetRouteOverWrite added in v1.10.1

func (s *Server) SetRouteOverWrite(enabled bool)

func (*Server) SetServerAgent

func (s *Server) SetServerAgent(agent string)

SetServerAgent sets the ServerAgent for the server.

func (*Server) SetServerRoot

func (s *Server) SetServerRoot(root string)

SetServerRoot sets the document root for static service.

func (*Server) SetSessionIdName

func (s *Server) SetSessionIdName(name string)

func (*Server) SetSessionMaxAge

func (s *Server) SetSessionMaxAge(ttl time.Duration)

func (*Server) SetSessionStorage

func (s *Server) SetSessionStorage(storage gsession.Storage)

func (*Server) SetTLSConfig

func (s *Server) SetTLSConfig(tlsConfig *tls.Config)

SetTLSConfig sets custom TLS configuration and enables HTTPS feature for the server.

func (*Server) SetView

func (s *Server) SetView(view *gview.View)

SetView sets the View for the server.

func (*Server) SetWriteTimeout

func (s *Server) SetWriteTimeout(t time.Duration)

SetWriteTimeout sets the WriteTimeout for the server.

func (*Server) Shutdown

func (s *Server) Shutdown() error

关闭当前Web Server

func (*Server) Start

func (s *Server) Start() error

作为守护协程异步执行(当同一进程中存在多个Web Server时,需要采用这种方式执行), 需要结合Wait方式一起使用.

func (*Server) Status

func (s *Server) Status() int

获取当前服务器的状态

func (*Server) Use added in v1.11.0

func (s *Server) Use(handlers ...HandlerFunc)

Use is alias of BindMiddlewareDefault. See BindMiddlewareDefault.

type ServerConfig

type ServerConfig struct {
	Address           string            // Basic: Server listening address like ":port", multiple addresses joined using ','.
	HTTPSAddr         string            // Basic: HTTPS addresses, multiple addresses joined using char ','.
	HTTPSCertPath     string            // Basic: HTTPS certification file path.
	HTTPSKeyPath      string            // Basic: HTTPS key file path.
	TLSConfig         *tls.Config       // Basic: TLS configuration for use by ServeTLS and ListenAndServeTLS.
	Handler           http.Handler      // Basic: Request handler.
	ReadTimeout       time.Duration     // Basic: Maximum duration for reading the entire request, including the body.
	WriteTimeout      time.Duration     // Basic: Maximum duration before timing out writes of the response.
	IdleTimeout       time.Duration     // Basic: Maximum amount of time to wait for the next request when keep-alive is enabled.
	MaxHeaderBytes    int               // Basic: Maximum number of bytes the server will read parsing the request header's keys and values, including the request line.
	KeepAlive         bool              // Basic: Enable HTTP keep-alive.
	ServerAgent       string            // Basic: Server agent information.
	View              *gview.View       // Basic: View object for the server.
	Rewrites          map[string]string // Static: URI rewrite rules map.
	IndexFiles        []string          // Static: The index files for static folder.
	IndexFolder       bool              // Static: List sub-files when requesting folder; server responses HTTP status code 403 if false.
	ServerRoot        string            // Static: The root directory for static service.
	SearchPaths       []string          // Static: Additional searching directories for static service.
	StaticPaths       []staticPathItem  // Static: URI to directory mapping array.
	FileServerEnabled bool              // Static: Switch for static service.
	CookieMaxAge      time.Duration     // Cookie: Max TTL for cookie items.
	CookiePath        string            // Cookie: Cookie Path(also affects the default storage for session id).
	CookieDomain      string            // Cookie: Cookie Domain(also affects the default storage for session id).
	SessionMaxAge     time.Duration     // Session: Max TTL for session items.
	SessionIdName     string            // Session: Session id name.
	SessionPath       string            // Session: Session Storage directory path for storing session files.
	SessionStorage    gsession.Storage  // Session: Session Storage implementer.
	Logger            *glog.Logger      // Logging: Logger for server.
	LogPath           string            // Logging: Directory for storing logging files.
	LogStdout         bool              // Logging: Printing logging content to stdout.
	ErrorStack        bool              // Logging: Logging stack information when error.
	ErrorLogEnabled   bool              // Logging: Enable error logging files.
	ErrorLogPattern   string            // Logging: Error log file pattern like: error-{Ymd}.log
	AccessLogEnabled  bool              // Logging: Enable access logging files.
	AccessLogPattern  string            // Logging: Error log file pattern like: access-{Ymd}.log
	PProfEnabled      bool              // PProf: Enable PProf feature.
	PProfPattern      string            // PProf: PProf service pattern for router.
	FormParsingMemory int64             // Other: Max memory in bytes which can be used for parsing multimedia form.
	NameToUriType     int               // Other: Type for converting struct method name to URI when registering routes.
	RouteOverWrite    bool              // Other: Allow overwrite the route if duplicated.
	DumpRouterMap     bool              // Other: Whether automatically dump router map when server starts.
	Graceful          bool              // Other: Enable graceful reload feature for all servers of the process.
}

HTTP Server configuration.

func Config

func Config() ServerConfig

Config returns the default ServerConfig object. Note that, do not define this default configuration to local variable, as there're some pointer attributes that may be shared in different servers.

func ConfigFromMap

func ConfigFromMap(m map[string]interface{}) (ServerConfig, error)

ConfigFromMap creates and returns a ServerConfig object with given map.

type Session

type Session = gsession.Session

type StaticFile added in v1.11.4

type StaticFile struct {
	File  *gres.File // Resource file object.
	Path  string     // File path.
	IsDir bool       // Is directory.
}

StaticFile is the file struct for static file service.

type UploadFile added in v1.11.5

type UploadFile struct {
	*multipart.FileHeader
}

UploadFile wraps the multipart uploading file with more and convenient features.

func (*UploadFile) Save added in v1.11.5

func (f *UploadFile) Save(dirPath string, randomlyRename ...bool) (filename string, err error)

Save saves the single uploading file to directory path and returns the saved file name.

The parameter <dirPath> should be a directory path or it returns error.

The parameter <randomlyRename> specifies whether randomly renames the file name, which make sense if the <path> is a directory.

Note that it will overwrite the target file if there's already a same name file exist.

type UploadFiles added in v1.11.5

type UploadFiles []*UploadFile

UploadFiles is array type for *UploadFile.

func (UploadFiles) Save added in v1.11.5

func (fs UploadFiles) Save(dirPath string, randomlyRename ...bool) (filenames []string, err error)

Save saves all uploading files to specified directory path and returns the saved file names.

The parameter <dirPath> should be a directory path or it returns error.

The parameter <randomlyRename> specifies whether randomly renames all the file names.

type WebSocket

type WebSocket struct {
	*websocket.Conn
}

Source Files

Jump to

Keyboard shortcuts

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