ghttp

package
v1.4.7 Latest Latest
Warning

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

Go to latest
Published: Feb 1, 2019 License: MIT Imports: 50 Imported by: 0

Documentation

Overview

Package ghttp provides quite powerful HTTP server and simple client implementations.

Index

Constants

View Source
const (
	SERVER_STATUS_STOPPED = 0 // Server状态:停止
	SERVER_STATUS_RUNNING = 1 // Server状态:运行
	HOOK_BEFORE_SERVE     = "BeforeServe"
	HOOK_AFTER_SERVE      = "AfterServe"
	HOOK_BEFORE_OUTPUT    = "BeforeOutput"
	HOOK_AFTER_OUTPUT     = "AfterOutput"
	HOOK_BEFORE_CLOSE     = "BeforeClose"
	HOOK_AFTER_CLOSE      = "AfterClose"
)
View Source
const (
	NAME_TO_URI_TYPE_DEFAULT  = 0 // 服务注册时对象和方法名称转换为URI时,全部转为小写,单词以'-'连接符号连接
	NAME_TO_URI_TYPE_FULLNAME = 1 // 不处理名称,以原有名称构建成URI
	NAME_TO_URI_TYPE_ALLLOWER = 2 // 仅转为小写,单词间不使用连接符号
	NAME_TO_URI_TYPE_CAMEL    = 3 // 采用驼峰命名方式

)
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 map[string]string) string

构建请求参数,将参数进行urlencode编码

func ConnectContent added in v1.4.6

func ConnectContent(url string, data ...string) string

func DeleteContent added in v1.4.6

func DeleteContent(url string, data ...string) string

DELETE请求并返回服务端结果(内部会自动读取服务端返回结果并关闭缓冲区指针)

func GetContent added in v1.4.6

func GetContent(url string, data ...string) string

GET请求并返回服务端结果(内部会自动读取服务端返回结果并关闭缓冲区指针)

func HeadContent added in v1.4.6

func HeadContent(url string, data ...string) string

func OptionsContent added in v1.4.6

func OptionsContent(url string, data ...string) string

func PatchContent added in v1.4.6

func PatchContent(url string, data ...string) string

func PostContent added in v1.4.6

func PostContent(url string, data ...string) string

POST请求并返回服务端结果(内部会自动读取服务端返回结果并关闭缓冲区指针)

func PutContent added in v1.4.6

func PutContent(url string, data ...string) string

PUT请求并返回服务端结果(内部会自动读取服务端返回结果并关闭缓冲区指针)

func RequestContent added in v1.4.6

func RequestContent(method string, url string, data ...string) string

请求并返回服务端结果(内部会自动读取服务端返回结果并关闭缓冲区指针)

func TraceContent added in v1.4.6

func TraceContent(url string, data ...string) string

func Wait

func Wait()

阻塞等待所有Web Server停止,常用于多Web Server场景,以及需要将Web Server异步运行的场景 这是一个与进程相关的方法

Types

type Client

type Client struct {
	http.Client // 底层http client对象
	// contains filtered or unexported fields
}

http客户端

func NewClient

func NewClient() *Client

http客户端对象指针

func (*Client) Connect

func (c *Client) Connect(url, data string) (*ClientResponse, error)

func (*Client) ConnectContent added in v1.4.6

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

func (*Client) Delete

func (c *Client) Delete(url, data string) (*ClientResponse, error)

DELETE请求

func (*Client) DeleteContent added in v1.4.6

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

DELETE请求并返回服务端结果(内部会自动读取服务端返回结果并关闭缓冲区指针)

func (*Client) DoRequest

func (c *Client) DoRequest(method, url string, data []byte) (*ClientResponse, error)

请求并返回response对象,该方法支持二进制提交数据

func (*Client) DoRequestContent added in v1.4.6

func (c *Client) DoRequestContent(method string, url string, data ...string) string

请求并返回服务端结果(内部会自动读取服务端返回结果并关闭缓冲区指针)

func (*Client) Get

func (c *Client) Get(url string) (*ClientResponse, error)

GET请求

func (*Client) GetContent added in v1.4.6

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

GET请求并返回服务端结果(内部会自动读取服务端返回结果并关闭缓冲区指针)

func (*Client) Head

func (c *Client) Head(url, data string) (*ClientResponse, error)

func (*Client) HeadContent added in v1.4.6

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

func (*Client) Options

func (c *Client) Options(url, data string) (*ClientResponse, error)

func (*Client) OptionsContent added in v1.4.6

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

func (*Client) Patch

func (c *Client) Patch(url, data string) (*ClientResponse, error)

func (*Client) PatchContent added in v1.4.6

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

func (*Client) Post

func (c *Client) Post(url, data string) (*ClientResponse, error)

POST请求提交数据,默认使用表单方式提交数据(绝大部分场景下也是如此)。 如果服务端对Content-Type有要求,可使用Client对象进行请求,单独设置相关属性。 支持文件上传,需要字段格式为:FieldName=@file:

func (*Client) PostContent added in v1.4.6

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

POST请求并返回服务端结果(内部会自动读取服务端返回结果并关闭缓冲区指针)

func (*Client) Put

func (c *Client) Put(url, data string) (*ClientResponse, error)

PUT请求

func (*Client) PutContent added in v1.4.6

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

PUT请求并返回服务端结果(内部会自动读取服务端返回结果并关闭缓冲区指针)

func (*Client) SetBasicAuth

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

设置HTTP访问账号密码

func (*Client) SetHeader

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

设置HTTP Header

func (*Client) SetHeaderRaw added in v1.4.6

func (c *Client) SetHeaderRaw(header string)

通过字符串设置HTTP Header

func (*Client) SetPrefix added in v1.4.6

func (c *Client) SetPrefix(prefix string)

设置请求的URL前缀

func (*Client) SetTimeOut

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

设置请求过期时间

func (*Client) Trace

func (c *Client) Trace(url, data string) (*ClientResponse, error)

func (*Client) TraceContent added in v1.4.6

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

type ClientResponse

type ClientResponse struct {
	http.Response
}

客户端请求结果对象

func Connect

func Connect(url, data string) (*ClientResponse, error)

func Delete

func Delete(url, data string) (*ClientResponse, error)

func DoRequest

func DoRequest(method, url string, data []byte) (*ClientResponse, error)

该方法支持二进制提交数据

func Get

func Get(url string) (*ClientResponse, error)
func Head(url, data string) (*ClientResponse, error)

func Options

func Options(url, data string) (*ClientResponse, error)

func Patch

func Patch(url, data string) (*ClientResponse, error)

func Post

func Post(url, data string) (*ClientResponse, error)

func Put

func Put(url, data string) (*ClientResponse, error)

func Trace

func Trace(url, data string) (*ClientResponse, error)

func (*ClientResponse) Close

func (r *ClientResponse) Close()

关闭返回的HTTP链接

func (*ClientResponse) ReadAll

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

获取返回的数据

type Controller

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

控制器接口

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

COOKIE对象

func GetCookie

func GetCookie(r *Request) *Cookie

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

func (*Cookie) Contains added in v1.2.10

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

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

func (*Cookie) Get

func (c *Cookie) Get(key string) string

查询cookie

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, domain, path string)

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

func (*Cookie) SessionId

func (c *Cookie) SessionId() string

获取SessionId,不存在时则创建

func (*Cookie) Set

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

设置cookie,使用默认参数

func (*Cookie) SetCookie

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

设置cookie,带详细cookie参数

func (*Cookie) SetSessionId

func (c *Cookie) SetSessionId(id string)

设置SessionId

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) error

控制器注册

func (*Domain) BindControllerMethod

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

控制器方法注册,methods参数区分大小写

func (*Domain) BindControllerRest

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

RESTful控制器注册

func (*Domain) BindHandler

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

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

func (*Domain) BindHookHandler

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

绑定指定的hook回调函数, hook参数的值由ghttp server设定,参数不区分大小写 目前hook支持:Init/Shut

func (*Domain) BindHookHandlerByMap

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

通过map批量绑定回调函数

func (*Domain) BindObject

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

执行对象方法

func (*Domain) BindObjectMethod

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

执行对象方法注册,methods参数不区分大小写

func (*Domain) BindObjectRest

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

RESTful执行对象注册

func (*Domain) BindStatusHandler

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

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

func (*Domain) BindStatusHandlerByMap

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

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

func (*Domain) Group added in v1.3.8

func (d *Domain) Group(prefix ...string) *RouterGroup

获取分组路由对象

type GroupItem added in v1.3.8

type GroupItem = []interface{}

分组路由批量绑定项

type HandlerFunc

type HandlerFunc = func(r *Request)

HTTP注册函数

type LogHandler

type LogHandler func(r *Request, error ...interface{})

自定义日志处理方法类型

type Request

type Request struct {
	http.Request

	Id        int       // 请求id(唯一)
	Server    *Server   // 请求关联的服务器对象
	Cookie    *Cookie   // 与当前请求绑定的Cookie对象(并发安全)
	Session   *Session  // 与当前请求绑定的Session对象(并发安全)
	Response  *Response // 对应请求的返回数据操作对象
	Router    *Router   // 匹配到的路由对象
	EnterTime int64     // 请求进入时间(微秒)
	LeaveTime int64     // 请求完成时间(微秒)
	// contains filtered or unexported fields
}

请求对象

func (*Request) AddPost

func (r *Request) AddPost(key string, value string)

func (*Request) AddQuery

func (r *Request) AddQuery(key string, value string)

添加GET参数,构成[]string

func (*Request) AddRouterString

func (r *Request) AddRouterString(key, value string)

func (*Request) BasicAuth

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

设置HTTP基础账号密码认证,如果用户没有提交账号密码,那么提示用户输出信息。 验证成功之后返回true,否则返回false

func (*Request) Exit

func (r *Request) Exit()

仅退出当前逻辑执行函数, 如:服务函数、HOOK函数

func (*Request) ExitAll added in v1.4.6

func (r *Request) ExitAll()

退出当前请求执行,后续所有的服务逻辑流程(包括其他的HOOK)将不会执行

func (*Request) ExitHook added in v1.4.6

func (r *Request) ExitHook()

仅针对HOOK执行,默认情况下HOOK会按照优先级进行调用,当使用ExitHook后当前类型的后续HOOK将不会被调用

func (*Request) Get

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

获得指定名称的参数字符串(Router/GET/POST),同 GetRequestString 这是常用方法的简化别名

func (*Request) GetArray

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

func (*Request) GetClientIp

func (r *Request) GetClientIp() string

获取请求的客户端IP地址

func (*Request) GetFloat32

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

func (*Request) GetFloat64

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

func (*Request) GetFloats

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

func (*Request) GetHost

func (r *Request) GetHost() string

获取请求的服务端IP/域名

func (*Request) GetInt

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

func (*Request) GetInterfaces

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

func (*Request) GetInts

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

func (*Request) GetJson

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

获取原始json请求输入字符串,并解析为json对象

func (*Request) GetMap

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

func (*Request) GetParam added in v1.2.11

func (r *Request) GetParam(key string) gvar.VarRead

获取请求流程共享变量

func (*Request) GetPost

func (r *Request) GetPost(key string, def ...[]string) []string

获得post参数

func (*Request) GetPostArray

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

func (*Request) GetPostBool

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

func (*Request) GetPostFloat32

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

func (*Request) GetPostFloat64

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

func (*Request) GetPostFloats

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

func (*Request) GetPostInt

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

func (*Request) GetPostInterfaces

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

func (*Request) GetPostInts

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

func (*Request) GetPostMap

func (r *Request) GetPostMap(def ...map[string]string) map[string]string

获取指定键名的关联数组,并且给定当指定键名不存在时的默认值 需要注意的是,如果其中一个字段为数组形式,那么只会返回第一个元素,如果需要获取全部的元素,请使用GetPostArray获取特定字段内容

func (*Request) GetPostString

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

func (*Request) GetPostStrings

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

func (*Request) GetPostToStruct

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

将所有的request参数映射到struct属性上,参数object应当为一个struct对象的指针, mapping为非必需参数,自定义参数与属性的映射关系

func (*Request) GetPostUint

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

func (*Request) GetQuery

func (r *Request) GetQuery(key string, def ...[]string) []string

获得指定名称的get参数列表

func (*Request) GetQueryArray

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

func (*Request) GetQueryBool

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

func (*Request) GetQueryFloat32

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

func (*Request) GetQueryFloat64

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

func (*Request) GetQueryFloats

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

func (*Request) GetQueryInt

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

func (*Request) GetQueryInterfaces

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

func (*Request) GetQueryInts

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

func (*Request) GetQueryMap

func (r *Request) GetQueryMap(def ...map[string]string) map[string]string

获取指定键名的关联数组,并且给定当指定键名不存在时的默认值

func (*Request) GetQueryString

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

func (*Request) GetQueryStrings

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

func (*Request) GetQueryToStruct

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

将所有的get参数映射到struct属性上,参数object应当为一个struct对象的指针, mapping为非必需参数,自定义参数与属性的映射关系

func (*Request) GetQueryUint

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

func (*Request) GetRaw

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

获取原始请求输入字符串

func (*Request) GetReferer

func (r *Request) GetReferer() string

获得来源URL地址

func (*Request) GetRequest

func (r *Request) GetRequest(key string, def ...[]string) []string

获得router、post或者get提交的参数,如果有同名参数,那么按照router->get->post优先级进行覆盖

func (*Request) GetRequestArray

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

func (*Request) GetRequestBool

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

func (*Request) GetRequestFloat32

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

func (*Request) GetRequestFloat64

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

func (*Request) GetRequestFloats

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

func (*Request) GetRequestInt

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

func (*Request) GetRequestInterfaces

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

func (*Request) GetRequestInts

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

func (*Request) GetRequestMap

func (r *Request) GetRequestMap(def ...map[string]string) map[string]string

获取指定键名的关联数组,并且给定当指定键名不存在时的默认值 需要注意的是,如果其中一个字段为数组形式,那么只会返回第一个元素,如果需要获取全部的元素,请使用GetRequestArray获取特定字段内容

func (*Request) GetRequestString

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

func (*Request) GetRequestStrings

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

func (*Request) GetRequestToStruct

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

将所有的request参数映射到struct属性上,参数object应当为一个struct对象的指针, mapping为非必需参数,自定义参数与属性的映射关系

func (*Request) GetRequestUint

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

func (*Request) GetRequestVar

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

func (*Request) GetRouterArray

func (r *Request) GetRouterArray(key string) []string

获得路由解析参数

func (*Request) GetRouterString

func (r *Request) GetRouterString(key string) string

获得路由解析参数

func (*Request) GetString

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

func (*Request) GetStrings

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

func (*Request) GetToStruct

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

将所有的request参数映射到struct属性上,参数object应当为一个struct对象的指针, mapping为非必需参数,自定义参数与属性的映射关系

func (*Request) GetUint

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

func (*Request) GetVar

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

建议都用该参数替代参数获取

func (*Request) IsAjaxRequest

func (r *Request) IsAjaxRequest() bool

判断是否为AJAX请求

func (*Request) IsExited

func (r *Request) IsExited() bool

判断当前请求是否停止执行

func (*Request) IsFileRequest

func (r *Request) IsFileRequest() bool

判断是否为静态文件请求

func (*Request) SetParam added in v1.2.11

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

设置请求流程共享变量

func (*Request) SetPost

func (r *Request) SetPost(key string, value string)

设置POST参数,仅在ghttp.Server内有效,**注意并发安全性**

func (*Request) SetQuery

func (r *Request) SetQuery(key string, value string)

设置GET参数,仅在ghttp.Server内有效,**注意并发安全性**

func (*Request) SetRouterString

func (r *Request) SetRouterString(key, value string)

func (*Request) WebSocket

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

获取Web Socket连接对象(如果是非WS请求会失败,注意检查然会的error结果)

type Response

type Response struct {
	ResponseWriter
	Server *Server         // 所属Web Server
	Writer *ResponseWriter // ResponseWriter的别名
	// contains filtered or unexported fields
}

服务端请求返回对象。 注意该对象并没有实现http.ResponseWriter接口,而是依靠ghttp.ResponseWriter实现。

func (*Response) Buffer

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

获取当前缓冲区中的数据

func (*Response) BufferLength

func (r *Response) BufferLength() int

获取当前缓冲区中的数据大小

func (*Response) ClearBuffer

func (r *Response) ClearBuffer()

清空缓冲区内容

func (*Response) OutputBuffer

func (r *Response) OutputBuffer()

输出缓冲区数据到客户端

func (*Response) ParseTpl

func (r *Response) ParseTpl(tpl string, params gview.Params, funcmap ...map[string]interface{}) ([]byte, error)

解析模板文件,并返回模板内容

func (*Response) ParseTplContent

func (r *Response) ParseTplContent(content string, params gview.Params, funcmap ...map[string]interface{}) ([]byte, error)

解析并返回模板内容

func (*Response) RedirectBack

func (r *Response) RedirectBack()

返回location标识,引导客户端跳转到来源页面

func (*Response) RedirectTo

func (r *Response) RedirectTo(location string)

返回location标识,引导客户端跳转

func (*Response) ServeFile

func (r *Response) ServeFile(path string)

静态文件处理

func (*Response) ServeFileDownload added in v1.2.11

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

静态文件下载处理

func (*Response) SetAllowCrossDomainRequest

func (r *Response) SetAllowCrossDomainRequest(allowOrigin string, allowMethods string, maxAge ...int)

允许AJAX跨域访问

func (*Response) SetBuffer

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

手动设置缓冲区内容

func (*Response) Write

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

返回信息,任何变量自动转换为bytes

func (*Response) WriteJson

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

返回JSON

func (*Response) WriteJsonP

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

返回JSONP

func (*Response) WriteStatus

func (r *Response) WriteStatus(status int, content ...string)

返回HTTP Code状态码

func (*Response) WriteTpl

func (r *Response) WriteTpl(tpl string, params map[string]interface{}, funcmap ...map[string]interface{}) error

展示模板,可以给定模板参数,及临时的自定义模板函数

func (*Response) WriteTplContent

func (r *Response) WriteTplContent(content string, params map[string]interface{}, funcmap ...map[string]interface{}) error

展示模板内容,可以给定模板参数,及临时的自定义模板函数

func (*Response) WriteXml

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

返回XML

func (*Response) Writef

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

返回信息,支持自定义format格式

func (*Response) Writefln

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

返回信息,末尾增加换行标识符"\n"

func (*Response) Writeln

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

返回信息,末尾增加换行标识符"\n"

type ResponseWriter

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

自定义的ResponseWriter,用于写入流的控制

func (*ResponseWriter) OutputBuffer

func (w *ResponseWriter) OutputBuffer()

输出buffer数据到客户端

func (*ResponseWriter) Write

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

覆盖父级的WriteHeader方法

func (*ResponseWriter) WriteHeader

func (w *ResponseWriter) WriteHeader(code int)

覆盖父级的WriteHeader方法

type Router

type Router struct {
	Uri      string   // 注册时的pattern - uri
	Method   string   // 注册时的pattern - method
	Domain   string   // 注册时的pattern - domain
	RegRule  string   // 路由规则解析后对应的正则表达式
	RegNames []string // 路由规则解析后对应的变量名称数组
	Priority int      // 优先级,用于链表排序,值越大优先级越高
}

路由对象

type RouterGroup added in v1.3.8

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

分组路由对象

func (*RouterGroup) ALL added in v1.3.8

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

绑定所有的HTTP Method请求方式

func (*RouterGroup) Bind added in v1.3.8

func (g *RouterGroup) Bind(group string, items []GroupItem)

执行分组路由批量绑定

func (*RouterGroup) COMMON added in v1.4.6

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

绑定常用方法: GET/PUT/POST/DELETE

func (*RouterGroup) CONNECT added in v1.3.8

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

func (*RouterGroup) DELETE added in v1.3.8

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

func (*RouterGroup) GET added in v1.3.8

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

func (*RouterGroup) HEAD added in v1.3.8

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

func (*RouterGroup) OPTIONS added in v1.3.8

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

func (*RouterGroup) PATCH added in v1.3.8

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

func (*RouterGroup) POST added in v1.3.8

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

func (*RouterGroup) PUT added in v1.3.8

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

func (*RouterGroup) REST added in v1.3.8

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

REST路由注册

func (*RouterGroup) TRACE added in v1.3.8

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

type Server

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

Server结构体

func GetServer

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

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

func (*Server) AddSearchPath

func (s *Server) AddSearchPath(path string)

添加静态文件搜索**目录**,必须给定目录的绝对路径

func (*Server) AddStaticPath added in v1.2.11

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

添加URI与静态**目录**的映射

func (*Server) BindController

func (s *Server) BindController(pattern string, c Controller, methods ...string) error

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

func (*Server) BindControllerMethod

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

绑定路由到指定的方法执行

func (*Server) BindControllerRest

func (s *Server) BindControllerRest(pattern string, c Controller) error

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

func (*Server) BindHandler

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

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

func (*Server) BindHookHandler

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

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

func (*Server) BindHookHandlerByMap

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

通过map批量绑定回调函数

func (*Server) BindObject

func (s *Server) BindObject(pattern string, obj interface{}, methods ...string) error

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

func (*Server) BindObjectMethod

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

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

func (*Server) BindObjectRest

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

绑定对象到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

生成一个域名对象

func (*Server) DumpRoutesMap

func (s *Server) DumpRoutesMap()

打印展示路由表

func (*Server) EnableAdmin

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

开启服务管理支持

func (*Server) EnableHTTPS

func (s *Server) EnableHTTPS(certFile, keyFile string)

开启HTTPS支持,但是必须提供Cert和Key文件

func (*Server) EnablePprof

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

开启pprof支持

func (*Server) GetCookieDomain

func (s *Server) GetCookieDomain() string

获取http server参数 - CookieDomain

func (*Server) GetCookieMaxAge

func (s *Server) GetCookieMaxAge() int

获取http server参数 - CookieMaxAge

func (*Server) GetCookiePath

func (s *Server) GetCookiePath() string

获取http server参数 - CookiePath

func (*Server) GetLogHandler

func (s *Server) GetLogHandler() LogHandler

获取日志写入的回调函数

func (*Server) GetLogPath

func (s *Server) GetLogPath() string

获取日志目录

func (*Server) GetName

func (s *Server) GetName() string

获取WebServer名称

func (*Server) GetRouteMap

func (s *Server) GetRouteMap() string

获得路由表(格式化字符串)

func (*Server) GetSessionIdName

func (s *Server) GetSessionIdName() string

获取http server参数 - SessionIdName

func (*Server) GetSessionMaxAge

func (s *Server) GetSessionMaxAge() int

获取http server参数 - SessionMaxAge

func (*Server) Group added in v1.3.8

func (s *Server) Group(prefix ...string) *RouterGroup

获取分组路由对象

func (*Server) IsAccessLogEnabled

func (s *Server) IsAccessLogEnabled() bool

access log日志功能是否开启

func (*Server) IsErrorLogEnabled

func (s *Server) IsErrorLogEnabled() bool

error log日志功能是否开启

func (*Server) Restart

func (s *Server) Restart(newExeFilePath ...string) error

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

func (*Server) Run

func (s *Server) Run() error

阻塞执行监听

func (*Server) SetAccessLogEnabled

func (s *Server) SetAccessLogEnabled(enabled bool)

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

func (*Server) SetAddr

func (s *Server) SetAddr(addr string)

设置http server参数 - Addr

func (*Server) SetAllowIps

func (s *Server) SetAllowIps(ips []string)

func (*Server) SetConfig

func (s *Server) SetConfig(c ServerConfig)

http server setting设置 注意使用该方法进行http server配置时,需要配置所有的配置项,否则没有配置的属性将会默认变量为空

func (*Server) SetCookieDomain

func (s *Server) SetCookieDomain(domain string)

设置http server参数 - CookieDomain

func (*Server) SetCookieMaxAge

func (s *Server) SetCookieMaxAge(age int)

设置http server参数 - CookieMaxAge

func (*Server) SetCookiePath

func (s *Server) SetCookiePath(path string)

设置http server参数 - CookiePath

func (*Server) SetDenyIps

func (s *Server) SetDenyIps(ips []string)

func (*Server) SetDenyRoutes

func (s *Server) SetDenyRoutes(routes []string)

func (*Server) SetDumpRouteMap

func (s *Server) SetDumpRouteMap(enabled bool)

是否在程序启动时打印路由表信息

func (*Server) SetErrorLogEnabled

func (s *Server) SetErrorLogEnabled(enabled bool)

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

func (*Server) SetFileServerEnabled added in v1.2.11

func (s *Server) SetFileServerEnabled(enabled bool)

是否开启/关闭静态文件服务,当关闭时仅提供动态接口服务,路由性能会得到一定提升

func (*Server) SetGzipContentTypes

func (s *Server) SetGzipContentTypes(types []string)

func (*Server) SetHTTPSAddr

func (s *Server) SetHTTPSAddr(addr string)

设置http server参数 - HTTPS Addr

func (*Server) SetHTTPSPort

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

设置http server参数 - HTTPS Port

func (*Server) SetIdleTimeout

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

设置http server参数 - IdleTimeout

func (*Server) SetIndexFiles

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

设置http server参数 - IndexFiles,默认展示文件,如:index.html, index.htm

func (*Server) SetIndexFolder

func (s *Server) SetIndexFolder(enabled bool)

允许展示访问目录的文件列表

func (*Server) SetLogHandler

func (s *Server) SetLogHandler(handler LogHandler)

设置日志写入的回调函数

func (*Server) SetLogPath

func (s *Server) SetLogPath(path string)

设置日志目录

func (*Server) SetMaxHeaderBytes

func (s *Server) SetMaxHeaderBytes(b int)

设置http server参数 - MaxHeaderBytes

func (*Server) SetNameToUriType

func (s *Server) SetNameToUriType(t int)

服务注册时对象和方法名称转换为URI时的规则

func (*Server) SetPort

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

设置http server参数 - Port

func (*Server) SetReadTimeout

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

设置http server参数 - ReadTimeout

func (*Server) SetRewrite added in v1.3.0

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

设置URI重写规则

func (*Server) SetRewriteMap added in v1.3.0

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

设置URI重写规则(批量)

func (*Server) SetRouterCacheExpire added in v1.2.11

func (s *Server) SetRouterCacheExpire(expire int)

设置路由缓存过期时间(秒)

func (*Server) SetServerAgent

func (s *Server) SetServerAgent(agent string)

设置http server参数 - ServerAgent

func (*Server) SetServerRoot

func (s *Server) SetServerRoot(root string)

设置http server参数 - ServerRoot

func (*Server) SetSessionIdName

func (s *Server) SetSessionIdName(name string)

设置http server参数 - SessionIdName

func (*Server) SetSessionMaxAge

func (s *Server) SetSessionMaxAge(age int)

设置http server参数 - SessionMaxAge

func (*Server) SetWriteTimeout

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

设置http server参数 - WriteTimeout

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

获取当前服务器的状态

type ServerConfig

type ServerConfig struct {
	// 底层http对象配置
	Addr           string        // 监听IP和端口,监听本地所有IP使用":端口"(支持多个地址,使用","号分隔)
	HTTPSAddr      string        // HTTPS服务监听地址(支持多个地址,使用","号分隔)
	HTTPSCertPath  string        // HTTPS证书文件路径
	HTTPSKeyPath   string        // HTTPS签名文件路径
	Handler        http.Handler  // 默认的处理函数
	ReadTimeout    time.Duration // 读取超时
	WriteTimeout   time.Duration // 写入超时
	IdleTimeout    time.Duration // 等待超时
	MaxHeaderBytes int           // 最大的header长度

	// 静态文件配置
	IndexFiles        []string         // 默认访问的文件列表
	IndexFolder       bool             // 如果访问目录是否显示目录列表
	ServerAgent       string           // Server Agent
	ServerRoot        string           // 服务器服务的本地目录根路径(检索优先级比StaticPaths低)
	SearchPaths       []string         // 静态文件搜索目录(包含ServerRoot,按照优先级进行排序)
	StaticPaths       []staticPathItem // 静态文件目录映射(按照优先级进行排序)
	FileServerEnabled bool             // 是否允许静态文件服务(通过静态文件服务方法调用自动识别)

	// COOKIE
	CookieMaxAge int    // Cookie有效期
	CookiePath   string // Cookie有效Path(注意同时也会影响SessionID)
	CookieDomain string // Cookie有效Domain(注意同时也会影响SessionID)

	// SESSION
	SessionMaxAge int    // Session有效期
	SessionIdName string // SessionId名称

	// IP访问控制
	DenyIps  []string // 不允许访问的ip列表,支持ip前缀过滤,如: 10 将不允许10开头的ip访问
	AllowIps []string // 仅允许访问的ip列表,支持ip前缀过滤,如: 10 将仅允许10开头的ip访问

	// 路由访问控制
	DenyRoutes []string          // 不允许访问的路由规则列表
	Rewrites   map[string]string // URI Rewrite重写配置

	// 日志配置
	LogPath          string     // 存放日志的目录路径
	LogHandler       LogHandler // 自定义日志处理回调方法
	ErrorLogEnabled  bool       // 是否开启error log
	AccessLogEnabled bool       // 是否开启access log

	// 其他设置
	NameToUriType     int      // 服务注册时对象和方法名称转换为URI时的规则
	GzipContentTypes  []string // 允许进行gzip压缩的文件类型
	DumpRouteMap      bool     // 是否在程序启动时默认打印路由表信息
	RouterCacheExpire int      // 路由检索缓存过期时间(秒)
}

HTTP Server 设置结构体,静态配置

func Config

func Config() ServerConfig

获取默认的http server设置

type Session

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

SESSION对象

func GetSession

func GetSession(r *Request) *Session

获取或者生成一个session对象(延迟初始化)

func (*Session) BatchSet

func (s *Session) BatchSet(m map[string]interface{})

批量设置

func (*Session) Clear

func (s *Session) Clear()

清空session

func (*Session) Contains

func (s *Session) Contains(key string) bool

判断键名是否存在

func (*Session) Data

func (s *Session) Data() map[string]interface{}

获取当前session所有数据

func (*Session) Get

func (s *Session) Get(key string) interface{}

获取SESSION

func (*Session) GetBool

func (s *Session) GetBool(key string) bool

func (*Session) GetBytes

func (s *Session) GetBytes(key string) []byte

func (*Session) GetFloat32

func (s *Session) GetFloat32(key string) float32

func (*Session) GetFloat64

func (s *Session) GetFloat64(key string) float64

func (*Session) GetFloats

func (s *Session) GetFloats(key string) []float64

func (*Session) GetInt

func (s *Session) GetInt(key string) int

func (*Session) GetInt16

func (s *Session) GetInt16(key string) int16

func (*Session) GetInt32

func (s *Session) GetInt32(key string) int32

func (*Session) GetInt64

func (s *Session) GetInt64(key string) int64

func (*Session) GetInt8

func (s *Session) GetInt8(key string) int8

func (*Session) GetInterfaces

func (s *Session) GetInterfaces(key string) []interface{}

func (*Session) GetInts

func (s *Session) GetInts(key string) []int

func (*Session) GetString

func (s *Session) GetString(key string) string

func (*Session) GetStrings

func (s *Session) GetStrings(key string) []string

func (*Session) GetStruct

func (s *Session) GetStruct(key string, objPointer interface{}, attrMapping ...map[string]string) error

将变量转换为对象,注意 objPointer 参数必须为struct指针

func (*Session) GetTime

func (s *Session) GetTime(key string, format ...string) time.Time

func (*Session) GetTimeDuration

func (s *Session) GetTimeDuration(key string) time.Duration

func (*Session) GetUint

func (s *Session) GetUint(key string) uint

func (*Session) GetUint16

func (s *Session) GetUint16(key string) uint16

func (*Session) GetUint32

func (s *Session) GetUint32(key string) uint32

func (*Session) GetUint64

func (s *Session) GetUint64(key string) uint64

func (*Session) GetUint8

func (s *Session) GetUint8(key string) uint8

func (*Session) GetVar added in v1.2.11

func (s *Session) GetVar(key string) gvar.VarRead

获取SESSION,建议都用该方法获取参数

func (*Session) Id

func (s *Session) Id() string

获取SessionId

func (*Session) Remove

func (s *Session) Remove(key string)

删除session

func (*Session) Set

func (s *Session) Set(key string, value interface{})

设置session

func (*Session) Sets

func (s *Session) Sets(m map[string]interface{})

批量设置(BatchSet别名)

func (*Session) UpdateExpire

func (s *Session) UpdateExpire()

更新过期时间(如果用在守护进程中长期使用,需要手动调用进行更新,防止超时被清除)

type WebSocket

type WebSocket struct {
	*websocket.Conn
}

Jump to

Keyboard shortcuts

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