Documentation ¶
Overview ¶
Package ghttp provides powerful http server and simple client implements.
Index ¶
- Constants
- Variables
- func BuildParams(params interface{}, noUrlEncode ...bool) (encodedParamStr string)
- func MiddlewareCORS(r *Request)
- func MiddlewareHandlerResponse(r *Request)
- func MiddlewareJsonBody(r *Request)
- func RestartAllServer(ctx context.Context, newExeFilePath ...string) error
- func ShutdownAllServer(ctx context.Context) error
- func StartPProfServer(port int, pattern ...string)
- func Wait()
- type CORSOptions
- type Cookie
- func (c *Cookie) Contains(key string) bool
- func (c *Cookie) Flush()
- func (c *Cookie) Get(key string, def ...string) *gvar.Var
- func (c *Cookie) GetSessionId() string
- func (c *Cookie) Map() map[string]string
- func (c *Cookie) Remove(key string)
- func (c *Cookie) RemoveCookie(key, domain, path string)
- func (c *Cookie) Set(key, value string)
- func (c *Cookie) SetCookie(key, value, domain, path string, maxAge time.Duration, ...)
- func (c *Cookie) SetHttpCookie(httpCookie *http.Cookie)
- func (c *Cookie) SetSessionId(id string)
- type CookieOptions
- type DefaultHandlerResponse
- type Domain
- func (d *Domain) BindHandler(pattern string, handler interface{})
- func (d *Domain) BindHookHandler(pattern string, hook string, handler HandlerFunc)
- func (d *Domain) BindHookHandlerByMap(pattern string, hookMap map[string]HandlerFunc)
- func (d *Domain) BindMiddleware(pattern string, handlers ...HandlerFunc)
- func (d *Domain) BindMiddlewareDefault(handlers ...HandlerFunc)
- func (d *Domain) BindObject(pattern string, obj interface{}, methods ...string)
- func (d *Domain) BindObjectMethod(pattern string, obj interface{}, method string)
- func (d *Domain) BindObjectRest(pattern string, obj interface{})
- func (d *Domain) BindStatusHandler(status int, handler HandlerFunc)
- func (d *Domain) BindStatusHandlerByMap(handlerMap map[int]HandlerFunc)
- func (d *Domain) EnablePProf(pattern ...string)
- func (d *Domain) Group(prefix string, groups ...func(group *RouterGroup)) *RouterGroup
- func (d *Domain) Use(handlers ...HandlerFunc)
- type HandlerFunc
- type HandlerItem
- type Plugin
- type Request
- func (r *Request) Assign(key string, value interface{})
- func (r *Request) Assigns(data gview.Params)
- func (r *Request) BasicAuth(user, pass string, tips ...string) bool
- func (r *Request) Context() context.Context
- func (r *Request) Exit()
- func (r *Request) ExitAll()
- func (r *Request) ExitHook()
- func (r *Request) Get(key string, def ...interface{}) *gvar.Var
- func (r *Request) GetBody() []byte
- func (r *Request) GetBodyString() string
- func (r *Request) GetClientIp() string
- func (r *Request) GetCtx() context.Context
- func (r *Request) GetCtxVar(key interface{}, def ...interface{}) *gvar.Var
- func (r *Request) GetError() error
- func (r *Request) GetForm(key string, def ...interface{}) *gvar.Var
- func (r *Request) GetFormMap(kvMap ...map[string]interface{}) map[string]interface{}
- func (r *Request) GetFormMapStrStr(kvMap ...map[string]interface{}) map[string]string
- func (r *Request) GetFormMapStrVar(kvMap ...map[string]interface{}) map[string]*gvar.Var
- func (r *Request) GetFormStruct(pointer interface{}, mapping ...map[string]string) error
- func (r *Request) GetHandlerResponse() interface{}
- func (r *Request) GetHeader(key string) string
- func (r *Request) GetHost() string
- func (r *Request) GetJson() (*gjson.Json, error)
- func (r *Request) GetMap(def ...map[string]interface{}) map[string]interface{}
- func (r *Request) GetMapStrStr(def ...map[string]interface{}) map[string]string
- func (r *Request) GetMultipartFiles(name string) []*multipart.FileHeader
- func (r *Request) GetMultipartForm() *multipart.Form
- func (r *Request) GetPage(totalSize, pageSize int) *gpage.Page
- func (r *Request) GetParam(key string, def ...interface{}) *gvar.Var
- func (r *Request) GetQuery(key string, def ...interface{}) *gvar.Var
- func (r *Request) GetQueryMap(kvMap ...map[string]interface{}) map[string]interface{}
- func (r *Request) GetQueryMapStrStr(kvMap ...map[string]interface{}) map[string]string
- func (r *Request) GetQueryMapStrVar(kvMap ...map[string]interface{}) map[string]*gvar.Var
- func (r *Request) GetQueryStruct(pointer interface{}, mapping ...map[string]string) error
- func (r *Request) GetReferer() string
- func (r *Request) GetRemoteIp() string
- func (r *Request) GetRequest(key string, def ...interface{}) *gvar.Var
- func (r *Request) GetRequestMap(kvMap ...map[string]interface{}) map[string]interface{}
- func (r *Request) GetRequestMapStrStr(kvMap ...map[string]interface{}) map[string]string
- func (r *Request) GetRequestMapStrVar(kvMap ...map[string]interface{}) map[string]*gvar.Var
- func (r *Request) GetRequestStruct(pointer interface{}, mapping ...map[string]string) error
- func (r *Request) GetRouter(key string, def ...interface{}) *gvar.Var
- func (r *Request) GetRouterMap() map[string]string
- func (r *Request) GetSessionId() string
- func (r *Request) GetStruct(pointer interface{}, mapping ...map[string]string) error
- func (r *Request) GetUploadFile(name string) *UploadFile
- func (r *Request) GetUploadFiles(name string) UploadFiles
- func (r *Request) GetUrl() string
- func (r *Request) GetView() *gview.View
- func (r *Request) IsAjaxRequest() bool
- func (r *Request) IsExited() bool
- func (r *Request) IsFileRequest() bool
- func (r *Request) Parse(pointer interface{}) error
- func (r *Request) ParseForm(pointer interface{}) error
- func (r *Request) ParseQuery(pointer interface{}) error
- func (r *Request) ReloadParam()
- func (r *Request) SetCtx(ctx context.Context)
- func (r *Request) SetCtxVar(key interface{}, value interface{})
- func (r *Request) SetError(err error)
- func (r *Request) SetForm(key string, value interface{})
- func (r *Request) SetParam(key string, value interface{})
- func (r *Request) SetParamMap(data map[string]interface{})
- func (r *Request) SetQuery(key string, value interface{})
- func (r *Request) SetView(view *gview.View)
- func (r *Request) WebSocket() (*WebSocket, error)
- type Response
- func (r *Response) Buffer() []byte
- func (r *Response) BufferLength() int
- func (r *Response) BufferString() string
- func (r *Response) CORS(options CORSOptions)
- func (r *Response) CORSAllowedOrigin(options CORSOptions) bool
- func (r *Response) CORSDefault()
- func (r *Response) ClearBuffer()
- func (r *Response) DefaultCORSOptions() CORSOptions
- func (r *Response) Flush()
- func (r *Response) ParseTpl(tpl string, params ...gview.Params) (string, error)
- func (r *Response) ParseTplContent(content string, params ...gview.Params) (string, error)
- func (r *Response) ParseTplDefault(params ...gview.Params) (string, error)
- func (r *Response) RedirectBack(code ...int)
- func (r *Response) RedirectTo(location string, code ...int)
- func (r *Response) ServeFile(path string, allowIndex ...bool)
- func (r *Response) ServeFileDownload(path string, name ...string)
- func (r *Response) SetBuffer(data []byte)
- func (r *Response) Write(content ...interface{})
- func (r *Response) WriteExit(content ...interface{})
- func (r *Response) WriteJson(content interface{})
- func (r *Response) WriteJsonExit(content interface{})
- func (r *Response) WriteJsonP(content interface{})
- func (r *Response) WriteJsonPExit(content interface{})
- func (r *Response) WriteOver(content ...interface{})
- func (r *Response) WriteOverExit(content ...interface{})
- func (r *Response) WriteStatus(status int, content ...interface{})
- func (r *Response) WriteStatusExit(status int, content ...interface{})
- func (r *Response) WriteTpl(tpl string, params ...gview.Params) error
- func (r *Response) WriteTplContent(content string, params ...gview.Params) error
- func (r *Response) WriteTplDefault(params ...gview.Params) error
- func (r *Response) WriteXml(content interface{}, rootTag ...string)
- func (r *Response) WriteXmlExit(content interface{}, rootTag ...string)
- func (r *Response) Writef(format string, params ...interface{})
- func (r *Response) WritefExit(format string, params ...interface{})
- func (r *Response) Writefln(format string, params ...interface{})
- func (r *Response) WriteflnExit(format string, params ...interface{})
- func (r *Response) Writeln(content ...interface{})
- func (r *Response) WritelnExit(content ...interface{})
- type ResponseWriter
- func (w *ResponseWriter) Flush()
- func (w *ResponseWriter) Header() http.Header
- func (w *ResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error)
- func (w *ResponseWriter) RawWriter() http.ResponseWriter
- func (w *ResponseWriter) Write(data []byte) (int, error)
- func (w *ResponseWriter) WriteHeader(status int)
- type Router
- type RouterGroup
- func (g *RouterGroup) ALL(pattern string, object interface{}, params ...interface{}) *RouterGroup
- func (g *RouterGroup) ALLMap(m map[string]interface{})
- func (g *RouterGroup) Bind(handlerOrObject ...interface{}) *RouterGroup
- func (g *RouterGroup) CONNECT(pattern string, object interface{}, params ...interface{}) *RouterGroup
- func (g *RouterGroup) Clone() *RouterGroup
- func (g *RouterGroup) DELETE(pattern string, object interface{}, params ...interface{}) *RouterGroup
- func (g *RouterGroup) GET(pattern string, object interface{}, params ...interface{}) *RouterGroup
- func (g *RouterGroup) Group(prefix string, groups ...func(group *RouterGroup)) *RouterGroup
- func (g *RouterGroup) HEAD(pattern string, object interface{}, params ...interface{}) *RouterGroup
- func (g *RouterGroup) Hook(pattern string, hook string, handler HandlerFunc) *RouterGroup
- func (g *RouterGroup) Map(m map[string]interface{})
- func (g *RouterGroup) Middleware(handlers ...HandlerFunc) *RouterGroup
- func (g *RouterGroup) OPTIONS(pattern string, object interface{}, params ...interface{}) *RouterGroup
- func (g *RouterGroup) PATCH(pattern string, object interface{}, params ...interface{}) *RouterGroup
- func (g *RouterGroup) POST(pattern string, object interface{}, params ...interface{}) *RouterGroup
- func (g *RouterGroup) PUT(pattern string, object interface{}, params ...interface{}) *RouterGroup
- func (g *RouterGroup) REST(pattern string, object interface{}) *RouterGroup
- func (g *RouterGroup) TRACE(pattern string, object interface{}, params ...interface{}) *RouterGroup
- type RouterItem
- type Server
- func (s *Server) AddSearchPath(path string)
- func (s *Server) AddStaticPath(prefix string, path string)
- func (s *Server) BindHandler(pattern string, handler interface{})
- func (s *Server) BindHookHandler(pattern string, hook string, handler HandlerFunc)
- func (s *Server) BindHookHandlerByMap(pattern string, hookMap map[string]HandlerFunc)
- func (s *Server) BindMiddleware(pattern string, handlers ...HandlerFunc)
- func (s *Server) BindMiddlewareDefault(handlers ...HandlerFunc)
- func (s *Server) BindObject(pattern string, object interface{}, method ...string)
- func (s *Server) BindObjectMethod(pattern string, object interface{}, method string)
- func (s *Server) BindObjectRest(pattern string, object interface{})
- func (s *Server) BindStatusHandler(status int, handler HandlerFunc)
- func (s *Server) BindStatusHandlerByMap(handlerMap map[int]HandlerFunc)
- func (s *Server) Domain(domains string) *Domain
- func (s *Server) EnableAdmin(pattern ...string)
- func (s *Server) EnableHTTPS(certFile, keyFile string, tlsConfig ...*tls.Config)
- func (s *Server) EnablePProf(pattern ...string)
- func (s *Server) GetCookieDomain() string
- func (s *Server) GetCookieHttpOnly() bool
- func (s *Server) GetCookieMaxAge() time.Duration
- func (s *Server) GetCookiePath() string
- func (s *Server) GetCookieSameSite() http.SameSite
- func (s *Server) GetCookieSecure() bool
- func (s *Server) GetHandler() func(w http.ResponseWriter, r *http.Request)
- func (s *Server) GetIndexFiles() []string
- func (s *Server) GetListenedPort() int
- func (s *Server) GetListenedPorts() []int
- func (s *Server) GetLogPath() string
- func (s *Server) GetName() string
- func (s *Server) GetOpenApi() *goai.OpenApiV3
- func (s *Server) GetRoutes() []RouterItem
- func (s *Server) GetSessionCookieMaxAge() time.Duration
- func (s *Server) GetSessionIdName() string
- func (s *Server) GetSessionMaxAge() time.Duration
- func (s *Server) Group(prefix string, groups ...func(group *RouterGroup)) *RouterGroup
- func (s *Server) IsAccessLogEnabled() bool
- func (s *Server) IsErrorLogEnabled() bool
- func (s *Server) Logger() *glog.Logger
- func (s *Server) Plugin(plugin ...Plugin)
- func (s *Server) Run()
- func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request)
- func (s *Server) SetAccessLogEnabled(enabled bool)
- func (s *Server) SetAddr(address string)
- func (s *Server) SetClientMaxBodySize(maxSize int64)
- func (s *Server) SetConfig(c ServerConfig) error
- func (s *Server) SetConfigWithMap(m map[string]interface{}) error
- func (s *Server) SetCookieDomain(domain string)
- func (s *Server) SetCookieMaxAge(ttl time.Duration)
- func (s *Server) SetCookiePath(path string)
- func (s *Server) SetDumpRouterMap(enabled bool)
- func (s *Server) SetErrorLogEnabled(enabled bool)
- func (s *Server) SetErrorStack(enabled bool)
- func (s *Server) SetFileServerEnabled(enabled bool)
- func (s *Server) SetFormParsingMemory(maxMemory int64)
- func (s *Server) SetHTTPSAddr(address string)
- func (s *Server) SetHTTPSPort(port ...int)
- func (s *Server) SetHandler(h func(w http.ResponseWriter, r *http.Request))
- func (s *Server) SetIdleTimeout(t time.Duration)
- func (s *Server) SetIndexFiles(indexFiles []string)
- func (s *Server) SetIndexFolder(enabled bool)
- func (s *Server) SetKeepAlive(enabled bool)
- func (s *Server) SetListener(listeners ...net.Listener) error
- func (s *Server) SetLogLevel(level string)
- func (s *Server) SetLogPath(path string) error
- func (s *Server) SetLogStdout(enabled bool)
- func (s *Server) SetLogger(logger *glog.Logger)
- func (s *Server) SetMaxHeaderBytes(b int)
- func (s *Server) SetName(name string)
- func (s *Server) SetNameToUriType(t int)
- func (s *Server) SetOpenApiPath(path string)
- func (s *Server) SetPort(port ...int)
- func (s *Server) SetReadTimeout(t time.Duration)
- func (s *Server) SetRewrite(uri string, rewrite string)
- func (s *Server) SetRewriteMap(rewrites map[string]string)
- func (s *Server) SetRouteOverWrite(enabled bool)
- func (s *Server) SetServerAgent(agent string)
- func (s *Server) SetServerRoot(root string)
- func (s *Server) SetSessionCookieMaxAge(maxAge time.Duration)
- func (s *Server) SetSessionCookieOutput(enabled bool)
- func (s *Server) SetSessionIdName(name string)
- func (s *Server) SetSessionMaxAge(ttl time.Duration)
- func (s *Server) SetSessionStorage(storage gsession.Storage)
- func (s *Server) SetSwaggerPath(path string)
- func (s *Server) SetTLSConfig(tlsConfig *tls.Config)
- func (s *Server) SetView(view *gview.View)
- func (s *Server) SetWriteTimeout(t time.Duration)
- func (s *Server) Shutdown() error
- func (s *Server) Start() error
- func (s *Server) Status() int
- func (s *Server) Use(handlers ...HandlerFunc)
- type ServerConfig
- type Session
- type UploadFile
- type UploadFiles
- type WebSocket
Examples ¶
Constants ¶
const ( HeaderXUrlPath = "x-url-path" // Used for custom route handler, which does not change URL.Path. HookBeforeServe = "HOOK_BEFORE_SERVE" // Hook handler before route handler/file serving. HookAfterServe = "HOOK_AFTER_SERVE" // Hook handler after route handler/file serving. HookBeforeOutput = "HOOK_BEFORE_OUTPUT" // Hook handler before response output. HookAfterOutput = "HOOK_AFTER_OUTPUT" // Hook handler after response output. ServerStatusStopped = 0 ServerStatusRunning = 1 DefaultServerName = "default" DefaultDomainName = "default" HandlerTypeHandler = "handler" HandlerTypeObject = "object" HandlerTypeMiddleware = "middleware" HandlerTypeHook = "hook" )
const ( UriTypeDefault = 0 // Method names to the URI converting type, which converts name to its lower case and joins the words using char '-'. UriTypeFullName = 1 // Method names to the URI converting type, which does not convert to the method name. UriTypeAllLower = 2 // Method names to the URI converting type, which converts name to its lower case. UriTypeCamel = 3 // Method names to the URI converting type, which converts name to its camel case. )
const ( // WsMsgText TextMessage denotes a text data message. // The text message payload is interpreted as UTF-8 encoded text data. WsMsgText = websocket.TextMessage // WsMsgBinary BinaryMessage denotes a binary data message. WsMsgBinary = websocket.BinaryMessage // WsMsgClose 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. WsMsgClose = websocket.CloseMessage // WsMsgPing PingMessage denotes a ping control message. // The optional message payload is UTF-8 encoded text. WsMsgPing = websocket.PingMessage // WsMsgPong PongMessage denotes a pong control message. // The optional message payload is UTF-8 encoded text. WsMsgPong = websocket.PongMessage )
Variables ¶
var ( ErrNeedJsonBody = gerror.NewOption(gerror.Option{ Text: "the request body content should be JSON format", Code: gcode.CodeInvalidRequest, }) )
Functions ¶
func BuildParams ¶
BuildParams builds the request string for the http client. The `params` can be type of: string/[]byte/map/struct/*struct.
The optional parameter `noUrlEncode` specifies whether to ignore the url encoding for the data.
func MiddlewareCORS ¶
func MiddlewareCORS(r *Request)
MiddlewareCORS is a middleware handler for CORS with default options.
func MiddlewareHandlerResponse ¶
func MiddlewareHandlerResponse(r *Request)
MiddlewareHandlerResponse is the default middleware handling handler response object and its error.
func MiddlewareJsonBody ¶ added in v2.1.3
func MiddlewareJsonBody(r *Request)
MiddlewareJsonBody validates and returns request body whether JSON format.
func RestartAllServer ¶
RestartAllServer restarts all the servers of the process. The optional parameter `newExeFilePath` specifies the new binary file for creating process.
func ShutdownAllServer ¶
ShutdownAllServer shuts down all servers of current process.
func StartPProfServer ¶
StartPProfServer starts and runs a new server for pprof.
Types ¶
type CORSOptions ¶
type CORSOptions struct { AllowDomain []string // Used for allowing requests from custom domains AllowOrigin string // Access-Control-Allow-Origin AllowCredentials string // Access-Control-Allow-Credentials ExposeHeaders string // Access-Control-Expose-Headers MaxAge int // Access-Control-Max-Age AllowMethods string // Access-Control-Allow-Methods AllowHeaders string // Access-Control-Allow-Headers }
CORSOptions is the options for CORS feature. See https://www.w3.org/TR/cors/ .
type Cookie ¶
type Cookie struct {
// contains filtered or unexported fields
}
Cookie for HTTP COOKIE management.
func GetCookie ¶
GetCookie creates or retrieves a cookie object with given request. It retrieves and returns an existing cookie object if it already exists with given request. It creates and returns a new cookie object if it does not exist with given request.
func (*Cookie) Get ¶
Get retrieves and returns the value with specified key. It returns `def` if specified key does not exist and `def` is given.
func (*Cookie) GetSessionId ¶
GetSessionId retrieves and returns the session id from cookie.
func (*Cookie) Remove ¶
Remove deletes specified key and its value from cookie using default domain and path. It actually tells the http client that the cookie is expired, do not send it to server next time.
func (*Cookie) RemoveCookie ¶
RemoveCookie deletes specified key and its value from cookie using given domain and path. It actually tells the http client that the cookie is expired, do not send it to server next time.
func (*Cookie) SetCookie ¶
func (c *Cookie) SetCookie(key, value, domain, path string, maxAge time.Duration, options ...CookieOptions)
SetCookie sets cookie item with given domain, path and expiration age. The optional parameter `options` specifies extra security configurations, which is usually empty.
func (*Cookie) SetHttpCookie ¶
SetHttpCookie sets cookie with *http.Cookie.
func (*Cookie) SetSessionId ¶
SetSessionId sets session id in the cookie.
type CookieOptions ¶
type CookieOptions struct { SameSite http.SameSite // cookie SameSite property Secure bool // cookie Secure property HttpOnly bool // cookie HttpOnly property }
CookieOptions provides security config for cookies
type DefaultHandlerResponse ¶
type DefaultHandlerResponse struct { Code int `json:"code" dc:"Error code"` Message string `json:"message" dc:"Error message"` Data interface{} `json:"data" dc:"Result data for certain request according API definition"` }
DefaultHandlerResponse is the default implementation of HandlerResponse.
type Domain ¶
type Domain struct {
// contains filtered or unexported fields
}
Domain is used for route register for domains.
func (*Domain) BindHandler ¶
BindHandler binds the handler for the specified pattern.
func (*Domain) BindHookHandler ¶
func (d *Domain) BindHookHandler(pattern string, hook string, handler HandlerFunc)
BindHookHandler binds the hook handler for the specified pattern.
func (*Domain) BindHookHandlerByMap ¶
func (d *Domain) BindHookHandlerByMap(pattern string, hookMap map[string]HandlerFunc)
BindHookHandlerByMap binds the hook handler for the specified pattern.
func (*Domain) BindMiddleware ¶
func (d *Domain) BindMiddleware(pattern string, handlers ...HandlerFunc)
BindMiddleware binds the middleware for the specified pattern.
func (*Domain) BindMiddlewareDefault ¶
func (d *Domain) BindMiddlewareDefault(handlers ...HandlerFunc)
BindMiddlewareDefault binds the default middleware for the specified pattern.
func (*Domain) BindObject ¶
BindObject binds the object for the specified pattern.
func (*Domain) BindObjectMethod ¶
BindObjectMethod binds the method for the specified pattern.
func (*Domain) BindObjectRest ¶
BindObjectRest binds the RESTful API for the specified pattern.
func (*Domain) BindStatusHandler ¶
func (d *Domain) BindStatusHandler(status int, handler HandlerFunc)
BindStatusHandler binds the status handler for the specified pattern.
func (*Domain) BindStatusHandlerByMap ¶
func (d *Domain) BindStatusHandlerByMap(handlerMap map[int]HandlerFunc)
BindStatusHandlerByMap binds the status handler for the specified pattern.
func (*Domain) EnablePProf ¶
EnablePProf enables PProf feature for server of specified domain.
func (*Domain) Group ¶
func (d *Domain) Group(prefix string, groups ...func(group *RouterGroup)) *RouterGroup
Group creates and returns a RouterGroup object, which is bound to a specified domain.
func (*Domain) Use ¶
func (d *Domain) Use(handlers ...HandlerFunc)
Use adds middleware to the domain.
type HandlerFunc ¶
type HandlerFunc = func(r *Request)
HandlerFunc is request handler function.
func WrapF ¶
func WrapF(f http.HandlerFunc) HandlerFunc
WrapF is a helper function for wrapping http.HandlerFunc and returns a ghttp.HandlerFunc.
func WrapH ¶
func WrapH(h http.Handler) HandlerFunc
WrapH is a helper function for wrapping http.Handler and returns a ghttp.HandlerFunc.
type HandlerItem ¶ added in v2.1.0
type HandlerItem struct { Id int // Unique handler item id mark. Name string // Handler name, which is automatically retrieved from runtime stack when registered. Type string // Handler type: object/handler/middleware/hook. Info handlerFuncInfo // Handler function information. InitFunc HandlerFunc // Initialization function when request enters the object (only available for object register type). ShutFunc HandlerFunc // Shutdown function when request leaves out the object (only available for object register type). Middleware []HandlerFunc // Bound middleware array. HookName string // Hook type name, only available for the hook type. Router *Router // Router object. Source string // Registering source file `path:line`. }
HandlerItem is the registered handler for route handling, including middleware and hook functions.
func (HandlerItem) MarshalJSON ¶ added in v2.1.0
func (item HandlerItem) MarshalJSON() ([]byte, error)
MarshalJSON implements the interface MarshalJSON for json.Marshal.
type Plugin ¶
type Plugin interface { Name() string // Name returns the name of the plugin. Author() string // Author returns the author of the plugin. Version() string // Version returns the version of the plugin, like "v1.0.0". Description() string // Description returns the description of the plugin. Install(s *Server) error // Install installs the plugin before the server starts. Remove() error // Remove removes the plugin. }
Plugin is the interface for server plugin.
type Request ¶
type Request struct { *http.Request Server *Server // Server. Cookie *Cookie // Cookie. Session *gsession.Session // Session. Response *Response // Corresponding Response of this request. Router *Router // Matched Router for this request. Note that it's not available in HOOK handler. EnterTime int64 // Request starting time in milliseconds. LeaveTime int64 // Request to end time in milliseconds. Middleware *middleware // Middleware manager. StaticFile *staticFile // Static file object for static file serving. // contains filtered or unexported fields }
Request is the context object for a request.
func RequestFromCtx ¶
RequestFromCtx retrieves and returns the Request object from context.
func (*Request) BasicAuth ¶
BasicAuth enables the http basic authentication feature with a given passport and password and asks client for authentication. It returns true if authentication success, else returns false if failure.
func (*Request) Context ¶
Context is alias for function GetCtx. This function overwrites the http.Request.Context function. See GetCtx.
func (*Request) ExitAll ¶
func (r *Request) ExitAll()
ExitAll exits executing of current and following HTTP handlers.
func (*Request) ExitHook ¶
func (r *Request) ExitHook()
ExitHook exits executing of current and following HTTP HOOK handlers.
func (*Request) Get ¶
Get is alias of GetRequest, which is one of the most commonly used functions for retrieving parameter. See r.GetRequest.
func (*Request) GetBody ¶
GetBody retrieves and returns request body content as bytes. It can be called multiple times retrieving the same body content.
func (*Request) GetBodyString ¶
GetBodyString retrieves and returns request body content as string. It can be called multiple times retrieving the same body content.
func (*Request) GetClientIp ¶
GetClientIp returns the client ip of this request without port. Note that this ip address might be modified by client header.
func (*Request) GetCtxVar ¶
GetCtxVar retrieves and returns a Var with a given key name. The optional parameter `def` specifies the default value of the Var if given `key` does not exist in the context.
func (*Request) GetError ¶
GetError returns the error occurs in the procedure of the request. It returns nil if there's no error.
func (*Request) GetForm ¶
GetForm retrieves and returns parameter `key` from form. It returns `def` if `key` does not exist in the form and `def` is given, or else it returns nil.
func (*Request) GetFormMap ¶
GetFormMap retrieves and returns all form parameters passed from client as map. The parameter `kvMap` specifies the keys retrieving from client parameters, the associated values are the default values if the client does not pass.
func (*Request) GetFormMapStrStr ¶
GetFormMapStrStr retrieves and returns all form parameters passed from client as map[string]string. The parameter `kvMap` specifies the keys retrieving from client parameters, the associated values are the default values if the client does not pass.
func (*Request) GetFormMapStrVar ¶
GetFormMapStrVar retrieves and returns all form parameters passed from client as map[string]*gvar.Var. The parameter `kvMap` specifies the keys retrieving from client parameters, the associated values are the default values if the client does not pass.
func (*Request) GetFormStruct ¶
GetFormStruct retrieves all form parameters passed from client and converts them to given struct object. Note that the parameter `pointer` is a pointer to the struct object. The optional parameter `mapping` is used to specify the key to attribute mapping.
func (*Request) GetHandlerResponse ¶
func (r *Request) GetHandlerResponse() interface{}
GetHandlerResponse retrieves and returns the handler response object and its error.
func (*Request) GetHost ¶
GetHost returns current request host name, which might be a domain or an IP without port.
func (*Request) GetJson ¶
GetJson parses current request content as JSON format, and returns the JSON object. Note that the request content is read from request BODY, not from any field of FORM.
func (*Request) GetMap ¶
GetMap is an alias and convenient function for GetRequestMap. See GetRequestMap.
func (*Request) GetMapStrStr ¶
GetMapStrStr is an alias and convenient function for GetRequestMapStrStr. See GetRequestMapStrStr.
func (*Request) GetMultipartFiles ¶
func (r *Request) GetMultipartFiles(name string) []*multipart.FileHeader
GetMultipartFiles parses and returns the post files array. Note that the request form should be type of multipart.
func (*Request) GetMultipartForm ¶
GetMultipartForm parses and returns the form as multipart forms.
func (*Request) GetPage ¶
GetPage creates and returns the pagination object for given `totalSize` and `pageSize`. NOTE THAT the page parameter name from clients is constantly defined as gpage.DefaultPageName for simplification and convenience.
func (*Request) GetParam ¶
GetParam returns custom parameter with a given name `key`. It returns `def` if `key` does not exist. It returns nil if `def` is not passed.
func (*Request) GetQuery ¶
GetQuery retrieves and return parameter with the given name `key` from query string and request body. It returns `def` if `key` does not exist in the query and `def` is given, or else it returns nil.
Note that if there are multiple parameters with the same name, the parameters are retrieved and overwrote in order of priority: query > body.
func (*Request) GetQueryMap ¶
GetQueryMap retrieves and returns all parameters passed from the client using HTTP GET method as the map. The parameter `kvMap` specifies the keys retrieving from client parameters, the associated values are the default values if the client does not pass.
Note that if there are multiple parameters with the same name, the parameters are retrieved and overwrote in order of priority: query > body.
func (*Request) GetQueryMapStrStr ¶
GetQueryMapStrStr retrieves and returns all parameters passed from the client using the HTTP GET method as a
map[string]string. The parameter `kvMap` specifies the keys
retrieving from client parameters, the associated values are the default values if the client does not pass.
func (*Request) GetQueryMapStrVar ¶
GetQueryMapStrVar retrieves and returns all parameters passed from the client using the HTTP GET method as map[string]*gvar.Var. The parameter `kvMap` specifies the keys retrieving from client parameters, the associated values are the default values if the client does not pass.
func (*Request) GetQueryStruct ¶
GetQueryStruct retrieves all parameters passed from the client using the HTTP GET method and converts them to a given struct object. Note that the parameter `pointer` is a pointer to the struct object. The optional parameter `mapping` is used to specify the key to attribute mapping.
func (*Request) GetReferer ¶
GetReferer returns referer of this request.
func (*Request) GetRemoteIp ¶
GetRemoteIp returns the ip from RemoteAddr.
func (*Request) GetRequest ¶
GetRequest retrieves and returns the parameter named `key` passed from the client and custom params as interface{}, no matter what HTTP method the client is using. The parameter `def` specifies the default value if the `key` does not exist.
GetRequest is one of the most commonly used functions for retrieving parameters.
Note that if there are multiple parameters with the same name, the parameters are retrieved and overwrote in order of priority: router < query < body < form < custom.
func (*Request) GetRequestMap ¶
GetRequestMap retrieves and returns all parameters passed from the client and custom params as the map, no matter what HTTP method the client is using. The parameter `kvMap` specifies the keys retrieving from client parameters, the associated values are the default values if the client does not pass the according keys.
GetRequestMap is one of the most commonly used functions for retrieving parameters.
Note that if there are multiple parameters with the same name, the parameters are retrieved and overwrote in order of priority: router < query < body < form < custom.
func (*Request) GetRequestMapStrStr ¶
GetRequestMapStrStr retrieve and returns all parameters passed from the client and custom params as map[string]string, no matter what HTTP method the client is using. The parameter `kvMap` specifies the keys retrieving from client parameters, the associated values are the default values if the client does not pass.
func (*Request) GetRequestMapStrVar ¶
GetRequestMapStrVar retrieve and returns all parameters passed from the client and custom params as map[string]*gvar.Var, no matter what HTTP method the client is using. The parameter `kvMap` specifies the keys retrieving from client parameters, the associated values are the default values if the client does not pass.
func (*Request) GetRequestStruct ¶
GetRequestStruct retrieves all parameters passed from the client and custom params no matter what HTTP method the client is using, and converts them to give the struct object. Note that the parameter `pointer` is a pointer to the struct object. The optional parameter `mapping` is used to specify the key to attribute mapping.
func (*Request) GetRouter ¶
GetRouter retrieves and returns the router value with given key name `key`. It returns `def` if `key` does not exist.
func (*Request) GetRouterMap ¶
GetRouterMap retrieves and returns a copy of the router map.
func (*Request) GetSessionId ¶
GetSessionId retrieves and returns session id from cookie or header.
func (*Request) GetStruct ¶
GetStruct is an alias and convenient function for GetRequestStruct. See GetRequestStruct.
func (*Request) GetUploadFile ¶
func (r *Request) GetUploadFile(name string) *UploadFile
GetUploadFile retrieves and returns the uploading file with specified form name. This function is used for retrieving single uploading file object, which is uploaded using multipart form content type.
It returns nil if retrieving failed or no form file with given name posted.
Note that the `name` is the file field name of the multipart form from client.
func (*Request) GetUploadFiles ¶
func (r *Request) GetUploadFiles(name string) UploadFiles
GetUploadFiles retrieves and returns multiple uploading files with specified form name. This function is used for retrieving multiple uploading file objects, which are uploaded using multipart form content type.
It returns nil if retrieving failed or no form file with given name posted.
Note that the `name` is the file field name of the multipart form from client.
func (*Request) IsAjaxRequest ¶
IsAjaxRequest checks and returns whether current request is an AJAX request.
func (*Request) IsFileRequest ¶
IsFileRequest checks and returns whether current request is serving file.
func (*Request) Parse ¶
Parse is the most commonly used function, which converts request parameters to struct or struct slice. It also automatically validates the struct or every element of the struct slice according to the validation tag of the struct.
The parameter `pointer` can be type of: *struct/**struct/*[]struct/*[]*struct.
It supports single and multiple struct converting: 1. Single struct, post content like: {"id":1, "name":"john"} or ?id=1&name=john 2. Multiple struct, post content like: [{"id":1, "name":"john"}, {"id":, "name":"smith"}]
TODO: Improve the performance by reducing duplicated reflect usage on the same variable across packages.
func (*Request) ParseForm ¶
ParseForm performs like function Parse, but only parses the form parameters or the body content.
func (*Request) ParseQuery ¶
ParseQuery performs like function Parse, but only parses the query parameters.
func (*Request) ReloadParam ¶
func (r *Request) ReloadParam()
ReloadParam is used for modifying request parameter. Sometimes, we want to modify request parameters through middleware, but directly modifying Request.Body is invalid, so it clears the parsed* marks of Request to make the parameters reparsed.
func (*Request) SetCtxVar ¶
func (r *Request) SetCtxVar(key interface{}, value interface{})
SetCtxVar sets custom parameter to context with key-value pairs.
func (*Request) SetParamMap ¶
SetParamMap sets custom parameter with key-value pair maps.
type Response ¶
type Response struct { *ResponseWriter // Underlying ResponseWriter. Server *Server // Parent server. Writer *ResponseWriter // Alias of ResponseWriter. Request *Request // According request. }
Response is the http response manager. Note that it implements the http.ResponseWriter interface with buffering feature.
func (*Response) BufferLength ¶
BufferLength returns the length of the buffered content.
func (*Response) BufferString ¶
BufferString returns the buffered content as string.
func (*Response) CORS ¶
func (r *Response) CORS(options CORSOptions)
CORS sets custom CORS options. See https://www.w3.org/TR/cors/ .
func (*Response) CORSAllowedOrigin ¶
func (r *Response) CORSAllowedOrigin(options CORSOptions) bool
CORSAllowedOrigin CORSAllowed checks whether the current request origin is allowed cross-domain.
func (*Response) CORSDefault ¶
func (r *Response) CORSDefault()
CORSDefault sets CORS with default CORS options, which allows any cross-domain request.
func (*Response) ClearBuffer ¶
func (r *Response) ClearBuffer()
ClearBuffer clears the response buffer.
func (*Response) DefaultCORSOptions ¶
func (r *Response) DefaultCORSOptions() CORSOptions
DefaultCORSOptions returns the default CORS options, which allows any cross-domain request.
func (*Response) Flush ¶
func (r *Response) Flush()
Flush outputs the buffer content to the client and clears the buffer.
func (*Response) ParseTpl ¶
ParseTpl parses given template file `tpl` with given template variables `params` and returns the parsed template content.
func (*Response) ParseTplContent ¶
ParseTplContent parses given template file `file` with given template parameters `params` and returns the parsed template content.
func (*Response) ParseTplDefault ¶
ParseTplDefault parses the default template file with params.
func (*Response) RedirectBack ¶
RedirectBack redirects the client back to referer. The optional parameter `code` specifies the http status code for redirecting, which commonly can be 301 or 302. It's 302 in default.
func (*Response) RedirectTo ¶
RedirectTo redirects the client to another location. The optional parameter `code` specifies the http status code for redirecting, which commonly can be 301 or 302. It's 302 in default.
func (*Response) ServeFileDownload ¶
ServeFileDownload serves file downloading to the response.
func (*Response) Write ¶
func (r *Response) Write(content ...interface{})
Write writes `content` to the response buffer.
func (*Response) WriteExit ¶
func (r *Response) WriteExit(content ...interface{})
WriteExit writes `content` to the response buffer and exits executing of current handler. The "Exit" feature is commonly used to replace usage of return statements in the handler, for convenience.
func (*Response) WriteJson ¶
func (r *Response) WriteJson(content interface{})
WriteJson writes `content` to the response with JSON format.
func (*Response) WriteJsonExit ¶
func (r *Response) WriteJsonExit(content interface{})
WriteJsonExit writes `content` to the response with JSON format and exits executing of current handler if success. The "Exit" feature is commonly used to replace usage of return statements in the handler, for convenience.
func (*Response) WriteJsonP ¶
func (r *Response) WriteJsonP(content interface{})
WriteJsonP writes `content` to the response with JSONP format.
Note that there should be a "callback" parameter in the request for JSONP format.
func (*Response) WriteJsonPExit ¶
func (r *Response) WriteJsonPExit(content interface{})
WriteJsonPExit writes `content` to the response with JSONP format and exits executing of current handler if success. The "Exit" feature is commonly used to replace usage of return statements in the handler, for convenience.
Note that there should be a "callback" parameter in the request for JSONP format.
func (*Response) WriteOver ¶
func (r *Response) WriteOver(content ...interface{})
WriteOver overwrites the response buffer with `content`.
func (*Response) WriteOverExit ¶
func (r *Response) WriteOverExit(content ...interface{})
WriteOverExit overwrites the response buffer with `content` and exits executing of current handler. The "Exit" feature is commonly used to replace usage of return statements in the handler, for convenience.
func (*Response) WriteStatus ¶
WriteStatus writes HTTP `status` and `content` to the response. Note that it does not set a Content-Type header here.
func (*Response) WriteStatusExit ¶
WriteStatusExit writes HTTP `status` and `content` to the response and exits executing of current handler if success. The "Exit" feature is commonly used to replace usage of return statements in the handler, for convenience.
func (*Response) WriteTpl ¶
WriteTpl parses and responses given template file. The parameter `params` specifies the template variables for parsing.
func (*Response) WriteTplContent ¶
WriteTplContent parses and responses the template content. The parameter `params` specifies the template variables for parsing.
func (*Response) WriteTplDefault ¶
WriteTplDefault parses and responses the default template file. The parameter `params` specifies the template variables for parsing.
func (*Response) WriteXmlExit ¶
WriteXmlExit writes `content` to the response with XML format and exits executing of current handler if success. The "Exit" feature is commonly used to replace usage of return statements in the handler, for convenience.
func (*Response) WritefExit ¶
WritefExit writes the response with fmt.Sprintf and exits executing of current handler. The "Exit" feature is commonly used to replace usage of return statements in the handler, for convenience.
func (*Response) WriteflnExit ¶
WriteflnExit writes the response with fmt.Sprintf and new line and exits executing of current handler. The "Exit" feature is commonly used to replace usage of return statement in the handler, for convenience.
func (*Response) Writeln ¶
func (r *Response) Writeln(content ...interface{})
Writeln writes the response with `content` and new line.
func (*Response) WritelnExit ¶
func (r *Response) WritelnExit(content ...interface{})
WritelnExit writes the response with `content` and new line and exits executing of current handler. The "Exit" feature is commonly used to replace usage of return statements in the handler, for convenience.
type ResponseWriter ¶
type ResponseWriter struct { Status int // HTTP status. // contains filtered or unexported fields }
ResponseWriter is the custom writer for http response.
func (*ResponseWriter) Flush ¶
func (w *ResponseWriter) Flush()
Flush outputs the buffer to clients and clears the buffer.
func (*ResponseWriter) Header ¶
func (w *ResponseWriter) Header() http.Header
Header implements the interface function of http.ResponseWriter.Header.
func (*ResponseWriter) Hijack ¶
func (w *ResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error)
Hijack implements the interface function of http.Hijacker.Hijack.
func (*ResponseWriter) RawWriter ¶
func (w *ResponseWriter) RawWriter() http.ResponseWriter
RawWriter returns the underlying ResponseWriter.
func (*ResponseWriter) Write ¶
func (w *ResponseWriter) Write(data []byte) (int, error)
Write implements the interface function of http.ResponseWriter.Write.
func (*ResponseWriter) WriteHeader ¶
func (w *ResponseWriter) WriteHeader(status int)
WriteHeader implements the interface of http.ResponseWriter.WriteHeader.
type Router ¶
type Router struct { Uri string // URI. Method string // HTTP method Domain string // Bound domain. RegRule string // Parsed regular expression for route matching. RegNames []string // Parsed router parameter names. Priority int // Just for reference. }
Router object.
type RouterGroup ¶
type RouterGroup struct {
// contains filtered or unexported fields
}
RouterGroup is a group wrapping multiple routes and middleware.
func (*RouterGroup) ALL ¶
func (g *RouterGroup) ALL(pattern string, object interface{}, params ...interface{}) *RouterGroup
ALL register a http handler to give the route pattern and all http methods.
func (*RouterGroup) ALLMap ¶
func (g *RouterGroup) ALLMap(m map[string]interface{})
ALLMap registers http handlers for http methods using map.
func (*RouterGroup) Bind ¶
func (g *RouterGroup) Bind(handlerOrObject ...interface{}) *RouterGroup
Bind does batch route registering feature for a router group.
func (*RouterGroup) CONNECT ¶
func (g *RouterGroup) CONNECT(pattern string, object interface{}, params ...interface{}) *RouterGroup
CONNECT registers a http handler to give the route pattern and the http method: CONNECT.
func (*RouterGroup) Clone ¶
func (g *RouterGroup) Clone() *RouterGroup
Clone returns a new router group which is a clone of the current group.
func (*RouterGroup) DELETE ¶
func (g *RouterGroup) DELETE(pattern string, object interface{}, params ...interface{}) *RouterGroup
DELETE registers a http handler to give the route pattern and the http method: DELETE.
func (*RouterGroup) GET ¶
func (g *RouterGroup) GET(pattern string, object interface{}, params ...interface{}) *RouterGroup
GET registers a http handler to give the route pattern and the http method: GET.
func (*RouterGroup) Group ¶
func (g *RouterGroup) Group(prefix string, groups ...func(group *RouterGroup)) *RouterGroup
Group creates and returns a subgroup of the current router group.
func (*RouterGroup) HEAD ¶
func (g *RouterGroup) HEAD(pattern string, object interface{}, params ...interface{}) *RouterGroup
HEAD registers a http handler to give the route pattern and the http method: HEAD.
func (*RouterGroup) Hook ¶
func (g *RouterGroup) Hook(pattern string, hook string, handler HandlerFunc) *RouterGroup
Hook registers a hook to given route pattern.
func (*RouterGroup) Map ¶
func (g *RouterGroup) Map(m map[string]interface{})
Map registers http handlers for http methods using map.
func (*RouterGroup) Middleware ¶
func (g *RouterGroup) Middleware(handlers ...HandlerFunc) *RouterGroup
Middleware binds one or more middleware to the router group.
func (*RouterGroup) OPTIONS ¶
func (g *RouterGroup) OPTIONS(pattern string, object interface{}, params ...interface{}) *RouterGroup
OPTIONS register a http handler to give the route pattern and the http method: OPTIONS.
func (*RouterGroup) PATCH ¶
func (g *RouterGroup) PATCH(pattern string, object interface{}, params ...interface{}) *RouterGroup
PATCH registers a http handler to give the route pattern and the http method: PATCH.
func (*RouterGroup) POST ¶
func (g *RouterGroup) POST(pattern string, object interface{}, params ...interface{}) *RouterGroup
POST registers a http handler to give the route pattern and the http method: POST.
func (*RouterGroup) PUT ¶
func (g *RouterGroup) PUT(pattern string, object interface{}, params ...interface{}) *RouterGroup
PUT registers a http handler to give the route pattern and the http method: PUT.
func (*RouterGroup) REST ¶
func (g *RouterGroup) REST(pattern string, object interface{}) *RouterGroup
REST registers a http handler to give the route pattern according to REST rule.
func (*RouterGroup) TRACE ¶
func (g *RouterGroup) TRACE(pattern string, object interface{}, params ...interface{}) *RouterGroup
TRACE registers a http handler to give the route pattern and the http method: TRACE.
type RouterItem ¶
type RouterItem struct { Handler *HandlerItem // The handler. Server string // Server name. Address string // Listening address. Domain string // Bound domain. Type string // Router type. Middleware string // Bound middleware. Method string // Handler method name. Route string // Route URI. Priority int // Just for reference. IsServiceHandler bool // Is service handler. }
RouterItem is just for route dumps.
type Server ¶
type Server struct {
// contains filtered or unexported fields
}
Server wraps the http.Server and provides more rich features.
func GetServer ¶
func GetServer(name ...interface{}) *Server
GetServer creates and returns a server instance using given name and default configurations. Note that the parameter `name` should be unique for different servers. It returns an existing server instance if given `name` is already existing in the server mapping.
func (*Server) AddSearchPath ¶
AddSearchPath add searching directory path for static file service.
func (*Server) AddStaticPath ¶
AddStaticPath sets the uri to static directory path mapping for static file service.
func (*Server) BindHandler ¶
BindHandler registers a handler function to server with a given pattern.
Note that the parameter `handler` can be type of: 1. func(*ghttp.Request) 2. func(context.Context, BizRequest)(BizResponse, error)
func (*Server) BindHookHandler ¶
func (s *Server) BindHookHandler(pattern string, hook string, handler HandlerFunc)
BindHookHandler registers handler for specified hook.
func (*Server) BindHookHandlerByMap ¶
func (s *Server) BindHookHandlerByMap(pattern string, hookMap map[string]HandlerFunc)
BindHookHandlerByMap registers handler for specified hook.
func (*Server) BindMiddleware ¶
func (s *Server) BindMiddleware(pattern string, handlers ...HandlerFunc)
BindMiddleware registers one or more global middleware to the server. Global middleware can be used standalone without service handler, which intercepts all dynamic requests before or after service handler. The parameter `pattern` specifies what route pattern the middleware intercepts, which is usually a "fuzzy" pattern like "/:name", "/*any" or "/{field}".
func (*Server) BindMiddlewareDefault ¶
func (s *Server) BindMiddlewareDefault(handlers ...HandlerFunc)
BindMiddlewareDefault registers one or more global middleware to the server using default pattern "/*". Global middleware can be used standalone without service handler, which intercepts all dynamic requests before or after service handler.
func (*Server) BindObject ¶
BindObject registers object to server routes with a given pattern.
The optional parameter `method` is used to specify the method to be registered, which supports multiple method names; multiple methods are separated by char ',', case-sensitive.
func (*Server) BindObjectMethod ¶
BindObjectMethod registers specified method of the object to server routes with a given pattern.
The optional parameter `method` is used to specify the method to be registered, which does not support multiple method names but only one, case-sensitive.
func (*Server) BindObjectRest ¶
BindObjectRest registers object in REST API styles to server with a specified pattern.
func (*Server) BindStatusHandler ¶
func (s *Server) BindStatusHandler(status int, handler HandlerFunc)
BindStatusHandler registers handler for given status code.
func (*Server) BindStatusHandlerByMap ¶
func (s *Server) BindStatusHandlerByMap(handlerMap map[int]HandlerFunc)
BindStatusHandlerByMap registers handler for given status code using map.
func (*Server) Domain ¶
Domain creates and returns a domain object for management for one or more domains.
func (*Server) EnableAdmin ¶
EnableAdmin enables the administration feature for the process. The optional parameter `pattern` specifies the URI for the administration page.
func (*Server) EnableHTTPS ¶
EnableHTTPS enables HTTPS with given certification and key files for the server. The optional parameter `tlsConfig` specifies custom TLS configuration.
func (*Server) EnablePProf ¶
EnablePProf enables PProf feature for server.
func (*Server) GetCookieDomain ¶
GetCookieDomain returns CookieDomain of server.
func (*Server) GetCookieHttpOnly ¶
func (*Server) GetCookieMaxAge ¶
GetCookieMaxAge returns the CookieMaxAge of the server.
func (*Server) GetCookiePath ¶
GetCookiePath returns the CookiePath of server.
func (*Server) GetCookieSameSite ¶
GetCookieSameSite return CookieSameSite of server.
func (*Server) GetCookieSecure ¶
func (*Server) GetHandler ¶
func (s *Server) GetHandler() func(w http.ResponseWriter, r *http.Request)
GetHandler returns the request handler of the server.
func (*Server) GetIndexFiles ¶
GetIndexFiles retrieves and returns the index files from the server.
func (*Server) GetListenedPort ¶
GetListenedPort retrieves and returns one port which is listened by current server.
func (*Server) GetListenedPorts ¶
GetListenedPorts retrieves and returns the ports which are listened by current server.
func (*Server) GetOpenApi ¶
GetOpenApi returns the OpenApi specification management object of current server.
func (*Server) GetRoutes ¶
func (s *Server) GetRoutes() []RouterItem
GetRoutes retrieves and returns the router array.
func (*Server) GetSessionCookieMaxAge ¶
GetSessionCookieMaxAge returns the SessionCookieMaxAge of server.
func (*Server) GetSessionIdName ¶
GetSessionIdName returns the SessionIdName of server.
func (*Server) GetSessionMaxAge ¶
GetSessionMaxAge returns the SessionMaxAge of server.
func (*Server) Group ¶
func (s *Server) Group(prefix string, groups ...func(group *RouterGroup)) *RouterGroup
Group creates and returns a RouterGroup object.
func (*Server) IsAccessLogEnabled ¶
IsAccessLogEnabled checks whether the access log enabled.
func (*Server) IsErrorLogEnabled ¶
IsErrorLogEnabled checks whether the error log enabled.
func (*Server) Run ¶
func (s *Server) Run()
Run starts server listening in blocking way. It's commonly used for single server situation.
Example ¶
package main import ( "github.com/gogf/gf/v2/frame/g" "github.com/gogf/gf/v2/net/ghttp" ) func main() { s := g.Server() s.BindHandler("/", func(r *ghttp.Request) { r.Response.Write("hello world") }) s.SetPort(8999) s.Run() }
Output:
func (*Server) ServeHTTP ¶
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request)
ServeHTTP is the default handler for http request. It should not create new goroutine handling the request as it's called by am already created new goroutine from http.Server.
This function also makes serve implementing the interface of http.Handler.
func (*Server) SetAccessLogEnabled ¶
SetAccessLogEnabled enables/disables the access log.
func (*Server) SetAddr ¶
SetAddr sets the listening address for the server. The address is like ':80', '0.0.0.0:80', '127.0.0.1:80', '180.18.99.10:80', etc.
func (*Server) SetClientMaxBodySize ¶
SetClientMaxBodySize sets the ClientMaxBodySize for server.
func (*Server) SetConfig ¶
func (s *Server) SetConfig(c ServerConfig) error
SetConfig sets the configuration for the server.
func (*Server) SetConfigWithMap ¶
SetConfigWithMap sets the configuration for the server using map.
func (*Server) SetCookieDomain ¶
SetCookieDomain sets the CookieDomain for server.
func (*Server) SetCookieMaxAge ¶
SetCookieMaxAge sets the CookieMaxAge for server.
func (*Server) SetCookiePath ¶
SetCookiePath sets the CookiePath for server.
func (*Server) SetDumpRouterMap ¶
SetDumpRouterMap sets the DumpRouterMap for server. If DumpRouterMap is enabled, it automatically dumps the route map when server starts.
func (*Server) SetErrorLogEnabled ¶
SetErrorLogEnabled enables/disables the error log.
func (*Server) SetErrorStack ¶
SetErrorStack enables/disables the error stack feature.
func (*Server) SetFileServerEnabled ¶
SetFileServerEnabled enables/disables the static file service. It's the main switch for the static file service. When static file service configuration functions like SetServerRoot, AddSearchPath and AddStaticPath are called, this configuration is automatically enabled.
func (*Server) SetFormParsingMemory ¶
SetFormParsingMemory sets the FormParsingMemory for server.
func (*Server) SetHTTPSAddr ¶
SetHTTPSAddr sets the HTTPS listening ports for the server.
func (*Server) SetHTTPSPort ¶
SetHTTPSPort sets the HTTPS listening ports for the server. The listening ports can be multiple like: SetHTTPSPort(443, 500).
func (*Server) SetHandler ¶
func (s *Server) SetHandler(h func(w http.ResponseWriter, r *http.Request))
SetHandler sets the request handler for server.
func (*Server) SetIdleTimeout ¶
SetIdleTimeout sets the IdleTimeout for the server.
func (*Server) SetIndexFiles ¶
SetIndexFiles sets the index files for server.
func (*Server) SetIndexFolder ¶
SetIndexFolder enables/disables listing the sub-files if requesting a directory.
func (*Server) SetKeepAlive ¶
SetKeepAlive sets the KeepAlive for the server.
func (*Server) SetListener ¶ added in v2.1.0
SetListener set the custom listener for the server.
func (*Server) SetLogLevel ¶
SetLogLevel sets logging level by level string.
func (*Server) SetLogPath ¶
SetLogPath sets the log path for server. It logs content to file only if the log path is set.
func (*Server) SetLogStdout ¶
SetLogStdout sets whether output the logging content to stdout.
func (*Server) SetLogger ¶
SetLogger sets the logger for logging responsibility. Note that it cannot be set in runtime as there may be concurrent safety issue.
func (*Server) SetMaxHeaderBytes ¶
SetMaxHeaderBytes sets the MaxHeaderBytes for the server.
func (*Server) SetNameToUriType ¶
SetNameToUriType sets the NameToUriType for server.
func (*Server) SetOpenApiPath ¶
SetOpenApiPath sets the OpenApiPath for server.
func (*Server) SetPort ¶
SetPort sets the listening ports for the server. The listening ports can be multiple like: SetPort(80, 8080).
func (*Server) SetReadTimeout ¶
SetReadTimeout sets the ReadTimeout for the server.
func (*Server) SetRewrite ¶
SetRewrite sets rewrites for static URI for server.
func (*Server) SetRewriteMap ¶
SetRewriteMap sets the rewritten map for server.
func (*Server) SetRouteOverWrite ¶
SetRouteOverWrite sets the RouteOverWrite for server.
func (*Server) SetServerAgent ¶
SetServerAgent sets the ServerAgent for the server.
func (*Server) SetServerRoot ¶
SetServerRoot sets the document root for static service.
func (*Server) SetSessionCookieMaxAge ¶
SetSessionCookieMaxAge sets the SessionCookieMaxAge for server.
func (*Server) SetSessionCookieOutput ¶
SetSessionCookieOutput sets the SetSessionCookieOutput for server.
func (*Server) SetSessionIdName ¶
SetSessionIdName sets the SessionIdName for server.
func (*Server) SetSessionMaxAge ¶
SetSessionMaxAge sets the SessionMaxAge for server.
func (*Server) SetSessionStorage ¶
SetSessionStorage sets the SessionStorage for server.
func (*Server) SetSwaggerPath ¶
SetSwaggerPath sets the SwaggerPath for server.
func (*Server) SetTLSConfig ¶
SetTLSConfig sets custom TLS configuration and enables HTTPS feature for the server.
func (*Server) SetWriteTimeout ¶
SetWriteTimeout sets the WriteTimeout for the server.
func (*Server) Start ¶
Start starts listening on configured port. This function does not block the process, you can use function Wait blocking the process.
func (*Server) Use ¶
func (s *Server) Use(handlers ...HandlerFunc)
Use is the alias of BindMiddlewareDefault. See BindMiddlewareDefault.
type ServerConfig ¶
type ServerConfig struct { // Service name, which is for service registry and discovery. Name string `json:"name"` // Address specifies the server listening address like "port" or ":port", // multiple addresses joined using ','. Address string `json:"address"` // HTTPSAddr specifies the HTTPS addresses, multiple addresses joined using char ','. HTTPSAddr string `json:"httpsAddr"` // Listeners specifies the custom listeners. Listeners []net.Listener `json:"listeners"` // HTTPSCertPath specifies certification file path for HTTPS service. HTTPSCertPath string `json:"httpsCertPath"` // HTTPSKeyPath specifies the key file path for HTTPS service. HTTPSKeyPath string `json:"httpsKeyPath"` // TLSConfig optionally provides a TLS configuration for use // by ServeTLS and ListenAndServeTLS. Note that this value is // cloned by ServeTLS and ListenAndServeTLS, so it's not // possible to modify the configuration with methods like // tls.Config.SetSessionTicketKeys. To use // SetSessionTicketKeys, use Server.Serve with a TLS Listener // instead. TLSConfig *tls.Config `json:"tlsConfig"` // Handler the handler for HTTP request. Handler func(w http.ResponseWriter, r *http.Request) `json:"-"` // ReadTimeout is the maximum duration for reading the entire // request, including the body. // // Because ReadTimeout does not let Handlers make per-request // decisions on each request body's acceptable deadline or // upload rate, most users will prefer to use // ReadHeaderTimeout. It is valid to use them both. ReadTimeout time.Duration `json:"readTimeout"` // WriteTimeout is the maximum duration before timing out // writes of the response. It is reset whenever a new // request's header is read. Like ReadTimeout, it does not // let Handlers make decisions on a per-request basis. WriteTimeout time.Duration `json:"writeTimeout"` // IdleTimeout is the maximum amount of time to wait for the // next request when keep-alives are enabled. If IdleTimeout // is zero, the value of ReadTimeout is used. If both are // zero, there is no timeout. IdleTimeout time.Duration `json:"idleTimeout"` // MaxHeaderBytes controls the maximum number of bytes the // server will read parsing the request header's keys and // values, including the request line. It does not limit the // size of the request body. // // It can be configured in configuration file using string like: 1m, 10m, 500kb etc. // It's 10240 bytes in default. MaxHeaderBytes int `json:"maxHeaderBytes"` // KeepAlive enables HTTP keep-alive. KeepAlive bool `json:"keepAlive"` // ServerAgent specifies the server agent information, which is wrote to // HTTP response header as "Server". ServerAgent string `json:"serverAgent"` // View specifies the default template view object for the server. View *gview.View `json:"view"` // Rewrites specifies the URI rewrite rules map. Rewrites map[string]string `json:"rewrites"` // IndexFiles specifies the index files for static folder. IndexFiles []string `json:"indexFiles"` // IndexFolder specifies if listing sub-files when requesting folder. // The server responses HTTP status code 403 if it is false. IndexFolder bool `json:"indexFolder"` // ServerRoot specifies the root directory for static service. ServerRoot string `json:"serverRoot"` // SearchPaths specifies additional searching directories for static service. SearchPaths []string `json:"searchPaths"` // StaticPaths specifies URI to directory mapping array. StaticPaths []staticPathItem `json:"staticPaths"` // FileServerEnabled is the global switch for static service. // It is automatically set enabled if any static path is set. FileServerEnabled bool `json:"fileServerEnabled"` // CookieMaxAge specifies the max TTL for cookie items. CookieMaxAge time.Duration `json:"cookieMaxAge"` // CookiePath specifies cookie path. // It also affects the default storage for session id. CookiePath string `json:"cookiePath"` // CookieDomain specifies cookie domain. // It also affects the default storage for session id. CookieDomain string `json:"cookieDomain"` // CookieSameSite specifies cookie SameSite property. // It also affects the default storage for session id. CookieSameSite string `json:"cookieSameSite"` // CookieSameSite specifies cookie Secure property. // It also affects the default storage for session id. CookieSecure bool `json:"cookieSecure"` // CookieSameSite specifies cookie HttpOnly property. // It also affects the default storage for session id. CookieHttpOnly bool `json:"cookieHttpOnly"` // SessionIdName specifies the session id name. SessionIdName string `json:"sessionIdName"` // SessionMaxAge specifies max TTL for session items. SessionMaxAge time.Duration `json:"sessionMaxAge"` // SessionPath specifies the session storage directory path for storing session files. // It only makes sense if the session storage is type of file storage. SessionPath string `json:"sessionPath"` // SessionStorage specifies the session storage. SessionStorage gsession.Storage `json:"sessionStorage"` // SessionCookieMaxAge specifies the cookie ttl for session id. // If it is set 0, it means it expires along with browser session. SessionCookieMaxAge time.Duration `json:"sessionCookieMaxAge"` // SessionCookieOutput specifies whether automatic outputting session id to cookie. SessionCookieOutput bool `json:"sessionCookieOutput"` Logger *glog.Logger `json:"logger"` // Logger specifies the logger for server. LogPath string `json:"logPath"` // LogPath specifies the directory for storing logging files. LogLevel string `json:"logLevel"` // LogLevel specifies the logging level for logger. LogStdout bool `json:"logStdout"` // LogStdout specifies whether printing logging content to stdout. ErrorStack bool `json:"errorStack"` // ErrorStack specifies whether logging stack information when error. ErrorLogEnabled bool `json:"errorLogEnabled"` // ErrorLogEnabled enables error logging content to files. ErrorLogPattern string `json:"errorLogPattern"` // ErrorLogPattern specifies the error log file pattern like: error-{Ymd}.log AccessLogEnabled bool `json:"accessLogEnabled"` // AccessLogEnabled enables access logging content to files. AccessLogPattern string `json:"accessLogPattern"` // AccessLogPattern specifies the error log file pattern like: access-{Ymd}.log PProfEnabled bool `json:"pprofEnabled"` // PProfEnabled enables PProf feature. PProfPattern string `json:"pprofPattern"` // PProfPattern specifies the PProf service pattern for router. OpenApiPath string `json:"openapiPath"` // OpenApiPath specifies the OpenApi specification file path. SwaggerPath string `json:"swaggerPath"` // SwaggerPath specifies the swagger UI path for route registering. // ClientMaxBodySize specifies the max body size limit in bytes for client request. // It can be configured in configuration file using string like: 1m, 10m, 500kb etc. // It's `8MB` in default. ClientMaxBodySize int64 `json:"clientMaxBodySize"` // FormParsingMemory specifies max memory buffer size in bytes which can be used for // parsing multimedia form. // It can be configured in configuration file using string like: 1m, 10m, 500kb etc. // It's 1MB in default. FormParsingMemory int64 `json:"formParsingMemory"` // NameToUriType specifies the type for converting struct method name to URI when // registering routes. NameToUriType int `json:"nameToUriType"` // RouteOverWrite allows to overwrite the route if duplicated. RouteOverWrite bool `json:"routeOverWrite"` // DumpRouterMap specifies whether automatically dumps router map when server starts. DumpRouterMap bool `json:"dumpRouterMap"` // Graceful enables graceful reload feature for all servers of the process. Graceful bool `json:"graceful"` // GracefulTimeout set the maximum survival time (seconds) of the parent process. GracefulTimeout uint8 `json:"gracefulTimeout"` }
ServerConfig is the HTTP Server configuration manager.
func ConfigFromMap ¶
func ConfigFromMap(m map[string]interface{}) (ServerConfig, error)
ConfigFromMap creates and returns a ServerConfig object with given map and default configuration object.
func NewConfig ¶
func NewConfig() ServerConfig
NewConfig creates and returns a ServerConfig object with default configurations. Note that, do not define this default configuration to local package variable, as there are some pointer attributes that may be shared in different servers.
type Session ¶
Session is actually an alias of gsession.Session, which is bound to a single request.
type UploadFile ¶
type UploadFile struct { *multipart.FileHeader `json:"-"` // contains filtered or unexported fields }
UploadFile wraps the multipart uploading file with more and convenient features.
func (UploadFile) MarshalJSON ¶ added in v2.1.0
func (f UploadFile) MarshalJSON() ([]byte, error)
MarshalJSON implements the interface MarshalJSON for json.Marshal.
func (*UploadFile) Save ¶
func (f *UploadFile) Save(dirPath string, randomlyRename ...bool) (filename string, err error)
Save saves the single uploading file to directory path and returns the saved file name.
The parameter `dirPath` should be a directory path, or it returns error.
Note that it will OVERWRITE the target file if there's already a same name file exist.
Example ¶
Custom saving file name.
package main import ( "github.com/gogf/gf/v2/frame/g" "github.com/gogf/gf/v2/net/ghttp" "github.com/gogf/gf/v2/os/gfile" ) func main() { s := g.Server() s.BindHandler("/upload", func(r *ghttp.Request) { file := r.GetUploadFile("TestFile") if file == nil { r.Response.Write("empty file") return } file.Filename = "MyCustomFileName.txt" fileName, err := file.Save(gfile.Temp()) if err != nil { r.Response.Write(err) return } r.Response.Write(fileName) }) s.SetPort(8999) s.Run() }
Output:
type UploadFiles ¶
type UploadFiles []*UploadFile
UploadFiles is an array type of *UploadFile.
func (UploadFiles) Save ¶
func (fs UploadFiles) Save(dirPath string, randomlyRename ...bool) (filenames []string, err error)
Save saves all uploading files to specified directory path and returns the saved file names.
The parameter `dirPath` should be a directory path or it returns error.
The parameter `randomlyRename` specifies whether randomly renames all the file names.
Source Files ¶
- ghttp.go
- ghttp_func.go
- ghttp_middleware_cors.go
- ghttp_middleware_handler_response.go
- ghttp_middleware_json_body.go
- ghttp_middleware_tracing.go
- ghttp_request.go
- ghttp_request_auth.go
- ghttp_request_middleware.go
- ghttp_request_param.go
- ghttp_request_param_ctx.go
- ghttp_request_param_file.go
- ghttp_request_param_form.go
- ghttp_request_param_page.go
- ghttp_request_param_param.go
- ghttp_request_param_query.go
- ghttp_request_param_request.go
- ghttp_request_param_router.go
- ghttp_request_view.go
- ghttp_response.go
- ghttp_response_cors.go
- ghttp_response_view.go
- ghttp_response_write.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_openapi.go
- ghttp_server_plugin.go
- ghttp_server_pprof.go
- ghttp_server_registry.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_handler.go
- ghttp_server_service_object.go
- ghttp_server_session.go
- ghttp_server_status.go
- ghttp_server_swagger.go
- ghttp_server_util.go
- ghttp_server_websocket.go