gf: github.com/gogf/gf/net/ghttp Index | Files

package ghttp

import "github.com/gogf/gf/net/ghttp"

Package ghttp provides powerful http server and simple client implements.

Index

Package Files

ghttp.go ghttp_client_api.go ghttp_client_bytes.go ghttp_client_config.go ghttp_client_content.go ghttp_client_request.go ghttp_client_response.go ghttp_controller.go ghttp_func.go ghttp_request.go ghttp_request_auth.go ghttp_request_hook.go ghttp_request_method_delete.go ghttp_request_method_post.go ghttp_request_method_put.go ghttp_request_method_query.go ghttp_request_middleware.go ghttp_request_params.go ghttp_request_request.go ghttp_request_router.go ghttp_response.go ghttp_response_cors.go ghttp_response_view.go ghttp_response_writer.go ghttp_server.go ghttp_server_admin.go ghttp_server_admin_process.go ghttp_server_admin_unix.go ghttp_server_config.go ghttp_server_config_cookie.go ghttp_server_config_logging.go ghttp_server_config_mess.go ghttp_server_config_route.go ghttp_server_config_session.go ghttp_server_config_static.go ghttp_server_cookie.go ghttp_server_domain.go ghttp_server_error_logger.go ghttp_server_graceful.go ghttp_server_handler.go ghttp_server_log.go ghttp_server_pprof.go ghttp_server_router.go ghttp_server_router_group.go ghttp_server_router_hook.go ghttp_server_router_middleware.go ghttp_server_router_serve.go ghttp_server_service_controller.go ghttp_server_service_handler.go ghttp_server_service_object.go ghttp_server_session.go ghttp_server_status.go ghttp_server_websocket.go

Constants

const (
    SERVER_STATUS_STOPPED = 0                    // Server状态:停止
    SERVER_STATUS_RUNNING = 1                    // Server状态:运行
    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"
)
const (
    URI_TYPE_DEFAULT  = 0 // 服务注册时对象和方法名称转换为URI时,全部转为小写,单词以'-'连接符号连接
    URI_TYPE_FULLNAME = 1 // 不处理名称,以原有名称构建成URI
    URI_TYPE_ALLLOWER = 2 // 仅转为小写,单词间不使用连接符号
    URI_TYPE_CAMEL    = 3 // 采用驼峰命名方式
)
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
)

func BuildParams Uses

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

构建请求参数,参数支持任意数据类型,常见参数类型为string/map。 如果参数为map类型,参数值将会进行urlencode编码;可以通过 noUrlEncode:true 参数取消编码。

func ConnectBytes Uses

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

func ConnectContent Uses

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

func DeleteBytes Uses

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

func DeleteContent Uses

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

func GetBytes Uses

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

func GetContent Uses

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

func HeadBytes Uses

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

func HeadContent Uses

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

func IsExitError Uses

func IsExitError(err interface{}) bool

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

func OptionsBytes Uses

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

func OptionsContent Uses

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

func PatchBytes Uses

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

func PatchContent Uses

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

func PostBytes Uses

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

func PostContent Uses

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

func PutBytes Uses

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

func PutContent Uses

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

func RequestBytes Uses

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

func RequestContent Uses

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

func RestartAllServer Uses

func RestartAllServer(newExeFilePath ...string) error

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

func SetGraceful Uses

func SetGraceful(enabled bool)

是否开启平滑重启特性

func ShutdownAllServer Uses

func ShutdownAllServer() error

关闭所有的WebServer

func TraceBytes Uses

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

func TraceContent Uses

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

func Wait Uses

func Wait()

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

type CORSOptions Uses

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
}

See https://www.w3.org/TR/cors/ .

type Client Uses

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

http客户端

func NewClient Uses

func NewClient() *Client

http客户端对象指针

func (*Client) BasicAuth Uses

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

链式操作, See SetBasicAuth

func (*Client) BrowserMode Uses

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

链式操作, See SetBrowserMode

func (*Client) Clone Uses

func (c *Client) Clone() *Client

克隆当前客户端对象,复制属性。

func (*Client) Connect Uses

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

func (*Client) ConnectBytes Uses

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

func (*Client) ConnectContent Uses

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

func (*Client) Delete Uses

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

DELETE请求

func (*Client) DeleteBytes Uses

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

func (*Client) DeleteContent Uses

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

func (*Client) DoRequest Uses

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

请求并返回response对象

func (*Client) Get Uses

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

GET请求

func (*Client) GetBytes Uses

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

func (*Client) GetContent Uses

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

func (*Client) Head Uses

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

func (*Client) HeadBytes Uses

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

func (*Client) HeadContent Uses

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

func (*Client) Options Uses

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

func (*Client) OptionsBytes Uses

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

func (*Client) OptionsContent Uses

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

func (*Client) Patch Uses

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

func (*Client) PatchBytes Uses

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

func (*Client) PatchContent Uses

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

func (*Client) Post Uses

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

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

func (*Client) PostBytes Uses

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

func (*Client) PostContent Uses

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

func (*Client) Put Uses

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

PUT请求

func (*Client) PutBytes Uses

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

func (*Client) PutContent Uses

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

func (*Client) RequestBytes Uses

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

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

func (*Client) RequestContent Uses

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

func (*Client) Retry Uses

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

链式操作, See SetRetry

func (*Client) SetBasicAuth Uses

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

设置HTTP访问账号密码

func (*Client) SetBrowserMode Uses

func (c *Client) SetBrowserMode(enabled bool)

是否模拟浏览器模式(自动保存提交COOKIE)

func (*Client) SetCookie Uses

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

设置COOKIE

func (*Client) SetCookieMap Uses

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

使用Map设置COOKIE

func (*Client) SetHeader Uses

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

设置HTTP Header

func (*Client) SetHeaderRaw Uses

func (c *Client) SetHeaderRaw(header string)

通过字符串设置HTTP Header

func (*Client) SetPrefix Uses

func (c *Client) SetPrefix(prefix string)

设置请求的URL前缀

func (*Client) SetRetry Uses

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

设置失败重试次数及间隔,失败仅针对网络请求失败情况。 重试间隔时间单位为秒。

func (*Client) SetTimeOut Uses

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

设置请求过期时间

func (*Client) TimeOut Uses

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

链式操作, See SetTimeOut

func (*Client) Trace Uses

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

func (*Client) TraceBytes Uses

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

func (*Client) TraceContent Uses

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

type ClientResponse Uses

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

客户端请求结果对象

func Connect Uses

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

func Delete Uses

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

func DoRequest Uses

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

func Get Uses

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

func Options Uses

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

func Patch Uses

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

func Post Uses

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

func Put Uses

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

func Trace Uses

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

func (*ClientResponse) Close Uses

func (r *ClientResponse) Close() error

关闭返回的HTTP链接

func (*ClientResponse) GetCookie Uses

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

获得返回的指定COOKIE值

func (*ClientResponse) ReadAll Uses

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

获取返回的数据(二进制).

func (*ClientResponse) ReadAllString Uses

func (r *ClientResponse) ReadAllString() string

获取返回的数据(字符串).

type Controller Uses

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

控制器接口

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

COOKIE对象,非并发安全。

func GetCookie Uses

func GetCookie(r *Request) *Cookie

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

func (*Cookie) Contains Uses

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

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

func (*Cookie) Get Uses

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

查询cookie

func (*Cookie) GetSessionId Uses

func (c *Cookie) GetSessionId() string

获得客户端提交的SessionId

func (*Cookie) Map Uses

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

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

func (*Cookie) Output Uses

func (c *Cookie) Output()

输出到客户端

func (*Cookie) Remove Uses

func (c *Cookie) Remove(key string)

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

func (*Cookie) RemoveCookie Uses

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

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

func (*Cookie) Set Uses

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

设置cookie,使用默认参数

func (*Cookie) SetCookie Uses

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

设置cookie,带详细cookie参数

func (*Cookie) SetSessionId Uses

func (c *Cookie) SetSessionId(id string)

设置SessionId到Cookie中

type CookieItem Uses

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

cookie项

type Domain Uses

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

域名管理器对象

func (*Domain) AddMiddleware Uses

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

注册中间件,绑定到全局路由规则("/*")上,中间件参数支持多个。

func (*Domain) BindController Uses

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

控制器注册

func (*Domain) BindControllerMethod Uses

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

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

func (*Domain) BindControllerRest Uses

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

RESTful控制器注册

func (*Domain) BindHandler Uses

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

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

func (*Domain) BindHookHandler Uses

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

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

func (*Domain) BindHookHandlerByMap Uses

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

通过map批量绑定回调函数

func (*Domain) BindMiddleware Uses

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

注册中间件,绑定到指定的路由规则上,中间件参数支持多个。

func (*Domain) BindObject Uses

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

执行对象方法

func (*Domain) BindObjectMethod Uses

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

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

func (*Domain) BindObjectRest Uses

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

RESTful执行对象注册

func (*Domain) BindStatusHandler Uses

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

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

func (*Domain) BindStatusHandlerByMap Uses

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

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

func (*Domain) Group Uses

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

获取分组路由对象(绑定域名)

type GroupItem Uses

type GroupItem = []interface{}

分组路由批量绑定项

type HandlerFunc Uses

type HandlerFunc = func(r *Request)

HTTP注册函数

type Middleware Uses

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

Middleware is the plugin for request handling.

func (*Middleware) Next Uses

func (m *Middleware) Next()

Next calls the next workflow handler.

type Request Uses

type Request struct {
    *http.Request
    Id         int               // 请求ID(当前Server对象唯一)
    Server     *Server           // 请求关联的服务器对象
    Cookie     *Cookie           // 与当前请求绑定的Cookie对象(并发安全)
    Session    *gsession.Session // 与当前请求绑定的Session对象(并发安全)
    Response   *Response         // 对应请求的返回数据操作对象
    Router     *Router           // 匹配到的路由对象
    EnterTime  int64             // 请求进入时间(微秒)
    LeaveTime  int64             // 请求完成时间(微秒)
    Middleware *Middleware       // 中间件功能调用对象
    // contains filtered or unexported fields
}

请求对象

func (*Request) BasicAuth Uses

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

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

func (*Request) Exit Uses

func (r *Request) Exit()

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

func (*Request) ExitAll Uses

func (r *Request) ExitAll()

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

func (*Request) ExitHook Uses

func (r *Request) ExitHook()

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

func (*Request) Get Uses

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

Get是GetRequest方法的别名,用于获得指定名称的参数值,注意键值可能是字符串、数组、Map类型。 大多数场景下,你可能需要的是 GetString/GetVar。

func (*Request) GetArray Uses

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

func (*Request) GetBool Uses

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

func (*Request) GetClientIp Uses

func (r *Request) GetClientIp() string

获取请求的客户端IP地址

func (*Request) GetDelete Uses

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

func (*Request) GetDeleteArray Uses

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

func (*Request) GetDeleteBool Uses

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

func (*Request) GetDeleteFloat32 Uses

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

func (*Request) GetDeleteFloat64 Uses

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

func (*Request) GetDeleteFloats Uses

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

func (*Request) GetDeleteInt Uses

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

func (*Request) GetDeleteInt32 Uses

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

func (*Request) GetDeleteInt64 Uses

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

func (*Request) GetDeleteInterfaces Uses

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

func (*Request) GetDeleteInts Uses

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

func (*Request) GetDeleteMap Uses

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

获取指定键名的关联数组,并且给定当指定键名不存在时的默认值。 当不指定键值对关联数组时,默认获取DELETE方式提交的所有的提交键值对数据。

func (*Request) GetDeleteMapStrStr Uses

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

func (*Request) GetDeleteMapStrVar Uses

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

func (*Request) GetDeleteString Uses

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

func (*Request) GetDeleteStrings Uses

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

func (*Request) GetDeleteToStruct Uses

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

func (*Request) GetDeleteUint Uses

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

func (*Request) GetDeleteUint32 Uses

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

func (*Request) GetDeleteUint64 Uses

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

func (*Request) GetDeleteVar Uses

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

func (*Request) GetFloat32 Uses

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

func (*Request) GetFloat64 Uses

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

func (*Request) GetFloats Uses

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

func (*Request) GetHost Uses

func (r *Request) GetHost() string

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

func (*Request) GetInt Uses

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

func (*Request) GetInterfaces Uses

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

func (*Request) GetInts Uses

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

func (*Request) GetJson Uses

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

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

func (*Request) GetMap Uses

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

func (*Request) GetMapStrStr Uses

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

func (*Request) GetMultipartFiles Uses

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

获取上传的文件列表

func (*Request) GetMultipartForm Uses

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

获取解析后的multipart.Form对象

func (*Request) GetParam Uses

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

获取请求流程共享变量

func (*Request) GetParamVar Uses

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

获取请求流程共享变量

func (*Request) GetPost Uses

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

func (*Request) GetPostArray Uses

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

func (*Request) GetPostBool Uses

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

func (*Request) GetPostFloat32 Uses

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

func (*Request) GetPostFloat64 Uses

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

func (*Request) GetPostFloats Uses

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

func (*Request) GetPostInt Uses

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

func (*Request) GetPostInt32 Uses

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

func (*Request) GetPostInt64 Uses

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

func (*Request) GetPostInterfaces Uses

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

func (*Request) GetPostInts Uses

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

func (*Request) GetPostMap Uses

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

获取指定键名的关联数组,并且给定当指定键名不存在时的默认值。 当不指定键值对关联数组时,默认获取POST方式提交的所有的提交键值对数据。

func (*Request) GetPostMapStrStr Uses

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

func (*Request) GetPostMapStrVar Uses

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

func (*Request) GetPostString Uses

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

func (*Request) GetPostStrings Uses

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

func (*Request) GetPostToStruct Uses

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

func (*Request) GetPostUint Uses

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

func (*Request) GetPostUint32 Uses

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

func (*Request) GetPostUint64 Uses

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

func (*Request) GetPostVar Uses

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

func (*Request) GetPut Uses

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

func (*Request) GetPutArray Uses

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

func (*Request) GetPutBool Uses

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

func (*Request) GetPutFloat32 Uses

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

func (*Request) GetPutFloat64 Uses

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

func (*Request) GetPutFloats Uses

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

func (*Request) GetPutInt Uses

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

func (*Request) GetPutInt32 Uses

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

func (*Request) GetPutInt64 Uses

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

func (*Request) GetPutInterfaces Uses

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

func (*Request) GetPutInts Uses

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

func (*Request) GetPutMap Uses

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

获取指定键名的关联数组,并且给定当指定键名不存在时的默认值。 当不指定键值对关联数组时,默认获取PUT方式提交的所有的提交键值对数据。

func (*Request) GetPutMapStrStr Uses

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

func (*Request) GetPutMapStrVar Uses

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

func (*Request) GetPutString Uses

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

func (*Request) GetPutStrings Uses

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

func (*Request) GetPutToStruct Uses

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

func (*Request) GetPutUint Uses

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

func (*Request) GetPutUint32 Uses

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

func (*Request) GetPutUint64 Uses

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

func (*Request) GetPutVar Uses

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

func (*Request) GetQuery Uses

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

func (*Request) GetQueryArray Uses

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

func (*Request) GetQueryBool Uses

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

func (*Request) GetQueryFloat32 Uses

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

func (*Request) GetQueryFloat64 Uses

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

func (*Request) GetQueryFloats Uses

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

func (*Request) GetQueryInt Uses

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

func (*Request) GetQueryInt32 Uses

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

func (*Request) GetQueryInt64 Uses

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

func (*Request) GetQueryInterfaces Uses

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

func (*Request) GetQueryInts Uses

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

func (*Request) GetQueryMap Uses

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

获取指定键名的关联数组,并且给定当指定键名不存在时的默认值。 当不指定键值对关联数组时,默认获取GET方式提交的所有的提交键值对数据。

func (*Request) GetQueryMapStrStr Uses

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

func (*Request) GetQueryMapStrVar Uses

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

func (*Request) GetQueryString Uses

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

func (*Request) GetQueryStrings Uses

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

func (*Request) GetQueryToStruct Uses

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

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

func (*Request) GetQueryUint Uses

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

func (*Request) GetQueryUint32 Uses

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

func (*Request) GetQueryUint64 Uses

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

func (*Request) GetQueryVar Uses

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

func (*Request) GetRaw Uses

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

获取原始请求输入二进制。

func (*Request) GetRawString Uses

func (r *Request) GetRawString() string

获取原始请求输入字符串。

func (*Request) GetReferer Uses

func (r *Request) GetReferer() string

获得请求来源URL地址

func (*Request) GetRequest Uses

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

获得router、post或者get提交的参数值,如果有同名参数, 那么按照 router->get->post->param->OtherHttpMethod 优先级进行覆盖。 注意获得参数值可能是字符串、数组、Map三种类型。

func (*Request) GetRequestArray Uses

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

func (*Request) GetRequestBool Uses

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

func (*Request) GetRequestFloat32 Uses

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

func (*Request) GetRequestFloat64 Uses

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

func (*Request) GetRequestFloats Uses

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

func (*Request) GetRequestInt Uses

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

func (*Request) GetRequestInt32 Uses

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

func (*Request) GetRequestInt64 Uses

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

func (*Request) GetRequestInterfaces Uses

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

func (*Request) GetRequestInts Uses

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

func (*Request) GetRequestMap Uses

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

func (*Request) GetRequestMapStrStr Uses

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

func (*Request) GetRequestMapStrVar Uses

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

func (*Request) GetRequestString Uses

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

func (*Request) GetRequestStrings Uses

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

func (*Request) GetRequestToStruct Uses

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

func (*Request) GetRequestUint Uses

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

func (*Request) GetRequestUint32 Uses

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

func (*Request) GetRequestUint64 Uses

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

func (*Request) GetRequestVar Uses

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

func (*Request) GetRouterString Uses

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

func (*Request) GetRouterValue Uses

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

获得路由解析参数

func (*Request) GetRouterVar Uses

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

获得路由解析参数

func (*Request) GetSessionId Uses

func (r *Request) GetSessionId() string

从Cookie和Header中查询SESSIONID

func (*Request) GetString Uses

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

func (*Request) GetStrings Uses

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

func (*Request) GetToStruct Uses

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

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

func (*Request) GetUint Uses

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

func (*Request) GetUrl Uses

func (r *Request) GetUrl() string

获得当前请求URL地址

func (*Request) GetVar Uses

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

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

func (*Request) IsAjaxRequest Uses

func (r *Request) IsAjaxRequest() bool

判断是否为AJAX请求

func (*Request) IsExited Uses

func (r *Request) IsExited() bool

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

func (*Request) IsFileRequest Uses

func (r *Request) IsFileRequest() bool

判断是否为静态文件请求

func (*Request) SetDelete Uses

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

func (*Request) SetParam Uses

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

设置请求流程共享变量

func (*Request) SetPost Uses

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

func (*Request) SetPut Uses

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

func (*Request) SetQuery Uses

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

func (*Request) SetRouterValue Uses

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

func (*Request) WebSocket Uses

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

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

type Response Uses

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

Response is the writer for response buffer. Note that it implements the http.ResponseWriter interface with buffering feature.

func (*Response) Buffer Uses

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

BufferString returns the buffer content as []byte.

func (*Response) BufferLength Uses

func (r *Response) BufferLength() int

BufferLength returns the length of the buffer content.

func (*Response) BufferString Uses

func (r *Response) BufferString() string

BufferString returns the buffer content as string.

func (*Response) CORS Uses

func (r *Response) CORS(options CORSOptions)

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

func (*Response) CORSAllowedOrigin Uses

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

CORSAllowed checks whether the current request origin is allowed CORS.

func (*Response) CORSDefault Uses

func (r *Response) CORSDefault()

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

func (*Response) ClearBuffer Uses

func (r *Response) ClearBuffer()

ClearBuffer clears the response buffer.

func (*Response) DefaultCORSOptions Uses

func (r *Response) DefaultCORSOptions() CORSOptions

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

func (*Response) Output Uses

func (r *Response) Output()

Output outputs the buffer content to the client.

func (*Response) ParseTpl Uses

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

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

func (*Response) ParseTplContent Uses

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

解析并返回模板内容

func (*Response) RedirectBack Uses

func (r *Response) RedirectBack()

RedirectBack redirects client back to referer.

func (*Response) RedirectTo Uses

func (r *Response) RedirectTo(location string)

RedirectTo redirects client to another location.

func (*Response) ServeFile Uses

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

ServeFile serves the file to the response.

func (*Response) ServeFileDownload Uses

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

ServeFileDownload serves file as file downloading to the response.

func (*Response) SetBuffer Uses

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

SetBuffer overwrites the buffer with <data>.

func (*Response) Write Uses

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

Write writes <content> to the response buffer.

func (*Response) WriteJson Uses

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

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

func (*Response) WriteJsonP Uses

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) WriteOver Uses

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

WriteOver overwrites the response buffer with <content>.

func (*Response) WriteStatus Uses

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

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

func (*Response) WriteTpl Uses

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

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

func (*Response) WriteTplContent Uses

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

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

func (*Response) WriteXml Uses

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

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

func (*Response) Writef Uses

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

Writef writes the response with fmt.Sprintf.

func (*Response) Writefln Uses

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

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

func (*Response) Writeln Uses

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

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

type ResponseWriter Uses

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

Custom ResponseWriter, which is used for controlling the output buffer.

func (*ResponseWriter) Header Uses

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

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

func (*ResponseWriter) Hijack Uses

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

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

func (*ResponseWriter) OutputBuffer Uses

func (w *ResponseWriter) OutputBuffer()

OutputBuffer outputs the buffer to client.

func (*ResponseWriter) RawWriter Uses

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

RawWriter returns the underlying ResponseWriter.

func (*ResponseWriter) Write Uses

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

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

func (*ResponseWriter) WriteHeader Uses

func (w *ResponseWriter) WriteHeader(status int)

WriteHeader implements the interface of http.ResponseWriter.WriteHeader.

type Router Uses

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

路由对象

type RouterGroup Uses

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

分组路由对象

func (*RouterGroup) ALL Uses

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

绑定所有的HTTP Method请求方式

func (*RouterGroup) Bind Uses

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

执行分组路由批量绑定

func (*RouterGroup) COMMON Uses

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

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

func (*RouterGroup) CONNECT Uses

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

func (*RouterGroup) Clone Uses

func (g *RouterGroup) Clone() *RouterGroup

func (*RouterGroup) DELETE Uses

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

func (*RouterGroup) GET Uses

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

func (*RouterGroup) Group Uses

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

层级递归创建分组路由注册项

func (*RouterGroup) HEAD Uses

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

func (*RouterGroup) Hook Uses

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

func (*RouterGroup) Middleware Uses

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

func (*RouterGroup) MiddlewarePattern Uses

func (g *RouterGroup) MiddlewarePattern(pattern string, handlers ...HandlerFunc) *RouterGroup

func (*RouterGroup) OPTIONS Uses

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

func (*RouterGroup) PATCH Uses

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

func (*RouterGroup) POST Uses

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

func (*RouterGroup) PUT Uses

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

func (*RouterGroup) REST Uses

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

func (*RouterGroup) TRACE Uses

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

type Server Uses

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

Server结构体

func GetServer Uses

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

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

func (*Server) AddSearchPath Uses

func (s *Server) AddSearchPath(path string)

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

func (*Server) AddStaticPath Uses

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

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

func (*Server) BindController Uses

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

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

func (*Server) BindControllerMethod Uses

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

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

func (*Server) BindControllerRest Uses

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

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

func (*Server) BindHandler Uses

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

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

func (*Server) BindHookHandler Uses

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

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

func (*Server) BindHookHandlerByMap Uses

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

通过map批量绑定回调函数

func (*Server) BindMiddleware Uses

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

注册中间件,绑定到指定的路由规则上,中间件参数支持多个。

func (*Server) BindMiddlewareDefault Uses

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

注册中间件,绑定到全局路由规则("/*")上,中间件参数支持多个。

func (*Server) BindObject Uses

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

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

func (*Server) BindObjectMethod Uses

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

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

func (*Server) BindObjectRest Uses

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

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

func (*Server) BindStatusHandler Uses

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

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

func (*Server) BindStatusHandlerByMap Uses

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

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

func (*Server) Domain Uses

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

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

func (*Server) DumpRoutesMap Uses

func (s *Server) DumpRoutesMap()

打印展示路由表

func (*Server) EnableAdmin Uses

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

开启服务管理支持

func (*Server) EnableHTTPS Uses

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

开启HTTPS支持,但是必须提供Cert和Key文件,tlsConfig为可选项

func (*Server) EnablePProf Uses

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

EnablePProf enables PProf feature for server.

func (*Server) GetCookieDomain Uses

func (s *Server) GetCookieDomain() string

获取http server参数 - CookieDomain

func (*Server) GetCookieMaxAge Uses

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

获取http server参数 - CookieMaxAge

func (*Server) GetCookiePath Uses

func (s *Server) GetCookiePath() string

获取http server参数 - CookiePath

func (*Server) GetLogPath Uses

func (s *Server) GetLogPath() string

获取日志目录

func (*Server) GetName Uses

func (s *Server) GetName() string

获取WebServer名称

func (*Server) GetRouteMap Uses

func (s *Server) GetRouteMap() string

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

func (*Server) GetSessionIdName Uses

func (s *Server) GetSessionIdName() string

获取http server参数 - SessionIdName

func (*Server) GetSessionMaxAge Uses

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

获取http server参数 - SessionMaxAge

func (*Server) Group Uses

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

获取分组路由对象

func (*Server) IsAccessLogEnabled Uses

func (s *Server) IsAccessLogEnabled() bool

access log日志功能是否开启

func (*Server) IsErrorLogEnabled Uses

func (s *Server) IsErrorLogEnabled() bool

error log日志功能是否开启

func (*Server) Run Uses

func (s *Server) Run()

阻塞执行监听

func (*Server) SetAccessLogEnabled Uses

func (s *Server) SetAccessLogEnabled(enabled bool)

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

func (*Server) SetAddr Uses

func (s *Server) SetAddr(address string)

设置http server参数 - Addr

func (*Server) SetAllowIps Uses

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

func (*Server) SetConfig Uses

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

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

func (*Server) SetConfigWithMap Uses

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

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

func (*Server) SetCookieDomain Uses

func (s *Server) SetCookieDomain(domain string)

设置http server参数 - CookieDomain

func (*Server) SetCookieMaxAge Uses

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

设置http server参数 - CookieMaxAge

func (*Server) SetCookiePath Uses

func (s *Server) SetCookiePath(path string)

设置http server参数 - CookiePath

func (*Server) SetDenyIps Uses

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

func (*Server) SetDenyRoutes Uses

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

func (*Server) SetDumpRouteMap Uses

func (s *Server) SetDumpRouteMap(enabled bool)

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

func (*Server) SetErrorLogEnabled Uses

func (s *Server) SetErrorLogEnabled(enabled bool)

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

func (*Server) SetErrorStack Uses

func (s *Server) SetErrorStack(enabled bool)

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

func (*Server) SetFileServerEnabled Uses

func (s *Server) SetFileServerEnabled(enabled bool)

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

func (*Server) SetFormParsingMemory Uses

func (s *Server) SetFormParsingMemory(maxMemory int64)

func (*Server) SetGzipContentTypes Uses

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

func (*Server) SetHTTPSAddr Uses

func (s *Server) SetHTTPSAddr(address string)

设置http server参数 - HTTPS Addr

func (*Server) SetHTTPSPort Uses

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

设置http server参数 - HTTPS Port

func (*Server) SetIdleTimeout Uses

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

设置http server参数 - IdleTimeout

func (*Server) SetIndexFiles Uses

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

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

func (*Server) SetIndexFolder Uses

func (s *Server) SetIndexFolder(enabled bool)

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

func (*Server) SetKeepAlive Uses

func (s *Server) SetKeepAlive(enabled bool)

设置KeepAlive

func (*Server) SetLogPath Uses

func (s *Server) SetLogPath(path string)

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

func (*Server) SetLogStdout Uses

func (s *Server) SetLogStdout(enabled bool)

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

func (*Server) SetMaxHeaderBytes Uses

func (s *Server) SetMaxHeaderBytes(b int)

设置http server参数 - MaxHeaderBytes

func (*Server) SetNameToUriType Uses

func (s *Server) SetNameToUriType(t int)

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

func (*Server) SetPort Uses

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

设置http server参数 - Port

func (*Server) SetReadTimeout Uses

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

设置http server参数 - ReadTimeout

func (*Server) SetRewrite Uses

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

设置URI重写规则

func (*Server) SetRewriteMap Uses

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

设置URI重写规则(批量)

func (*Server) SetRouterCacheExpire Uses

func (s *Server) SetRouterCacheExpire(expire int)

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

func (*Server) SetServerAgent Uses

func (s *Server) SetServerAgent(agent string)

设置http server参数 - ServerAgent

func (*Server) SetServerRoot Uses

func (s *Server) SetServerRoot(root string)

设置http server参数 - ServerRoot

func (*Server) SetSessionIdName Uses

func (s *Server) SetSessionIdName(name string)

设置http server参数 - SessionIdName

func (*Server) SetSessionMaxAge Uses

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

设置http server参数 - SessionMaxAge

func (*Server) SetSessionStorage Uses

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

设置http server参数 - SessionStorage

func (*Server) SetTLSConfig Uses

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

设置TLS配置对象

func (*Server) SetView Uses

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

设置模板引擎对象

func (*Server) SetWriteTimeout Uses

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

设置http server参数 - WriteTimeout

func (*Server) Shutdown Uses

func (s *Server) Shutdown() error

关闭当前Web Server

func (*Server) Start Uses

func (s *Server) Start() error

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

func (*Server) Status Uses

func (s *Server) Status() int

获取当前服务器的状态

type ServerConfig Uses

type ServerConfig struct {
    Address           string            // Server listening address like ":port", multiple addresses separated using ','
    HTTPSAddr         string            // HTTPS服务监听地址(支持多个地址,使用","号分隔)
    HTTPSCertPath     string            // HTTPS证书文件路径
    HTTPSKeyPath      string            // HTTPS签名文件路径
    Handler           http.Handler      // 默认的处理函数
    ReadTimeout       time.Duration     // 读取超时
    WriteTimeout      time.Duration     // 写入超时
    IdleTimeout       time.Duration     // 等待超时
    MaxHeaderBytes    int               // 最大的header长度
    TLSConfig         *tls.Config       // HTTPS证书配置
    KeepAlive         bool              // 是否开启长连接
    ServerAgent       string            // Server Agent
    View              *gview.View       // 模板引擎对象
    Rewrites          map[string]string // URI Rewrite重写配置
    IndexFiles        []string          // Static: 默认访问的文件列表
    IndexFolder       bool              // Static: 如果访问目录是否显示目录列表
    ServerRoot        string            // Static: 服务器服务的本地目录根路径(检索优先级比StaticPaths低)
    SearchPaths       []string          // Static: 静态文件搜索目录(包含ServerRoot,按照优先级进行排序)
    StaticPaths       []staticPathItem  // Static: 静态文件目录映射(按照优先级进行排序)
    FileServerEnabled bool              // Static: 是否允许静态文件服务(通过静态文件服务方法调用自动识别)
    CookieMaxAge      time.Duration     // Cookie: 有效期
    CookiePath        string            // Cookie: 有效Path(注意同时也会影响SessionID)
    CookieDomain      string            // Cookie: 有效Domain(注意同时也会影响SessionID)
    SessionMaxAge     time.Duration     // Session: 有效期
    SessionIdName     string            // Session: SessionId.
    SessionPath       string            // Session: Session Storage path for storing session files.
    SessionStorage    gsession.Storage  // Session: Session Storage implementer.
    DenyIps           []string          // Security: 不允许访问的ip列表,支持ip前缀过滤,如: 10 将不允许10开头的ip访问
    AllowIps          []string          // Security: 仅允许访问的ip列表,支持ip前缀过滤,如: 10 将仅允许10开头的ip访问
    DenyRoutes        []string          // Security: 不允许访问的路由规则列表
    Logger            *glog.Logger      // Logging: Custom logger for server.
    LogPath           string            // Logging: 存放日志的目录路径(默认为空,表示不写文件)
    LogStdout         bool              // Logging: 是否打印日志到终端(默认开启)
    ErrorStack        bool              // Logging: 当产生错误时打印调用链详细堆栈
    ErrorLogEnabled   bool              // Logging: 是否开启error log(默认开启)
    ErrorLogPattern   string            // Logging: Error log file pattern like: error-{Ymd}.log
    AccessLogEnabled  bool              // Logging: 是否开启access log(默认关闭)
    AccessLogPattern  string            // Logging: Error log file pattern like: access-{Ymd}.log
    PProfEnabled      bool              // PProf: Enable PProf feature or not.
    PProfPattern      string            // PProf: PProf pattern for router, it enables PProf feature if it's not empty.
    FormParsingMemory int64             // Mess: 表单解析内存限制(byte)
    NameToUriType     int               // Mess: 服务注册时对象和方法名称转换为URI时的规则
    GzipContentTypes  []string          // Mess: 允许进行gzip压缩的文件类型
    DumpRouteMap      bool              // Mess: 是否在程序启动时默认打印路由表信息
    RouterCacheExpire int               // Mess: 路由检索缓存过期时间(秒)
}

HTTP Server configuration.

func Config Uses

func Config() ServerConfig

获取默认的http server设置

func ConfigFromMap Uses

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

通过Map创建Config配置对象,Map没有传递的属性将会使用模块的默认值

type Session Uses

type Session = gsession.Session

type WebSocket Uses

type WebSocket struct {
    *websocket.Conn
}

Package ghttp imports 58 packages (graph) and is imported by 19 packages. Updated 2019-11-09. Refresh now. Tools for package owners.