Merge pull request #1684 from houseme/fix-1674

improve ignore and up websocket 1.5.0
This commit is contained in:
John Guo
2022-03-19 22:50:53 +08:00
committed by GitHub
47 changed files with 191 additions and 178 deletions

1
.gitignore vendored
View File

@ -13,7 +13,6 @@ pkg/
bin/
cbuild
**/.DS_Store
.vscode/
.test/
main
gf

View File

@ -40,8 +40,8 @@ github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.5.6 h1:BKbKCqvP6I+rmFHt06ZmyQtvB8xAkWdhFyr0ZUNZcxQ=
github.com/google/go-cmp v0.5.6/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/gorilla/websocket v1.4.2 h1:+/TMaTYc4QFitKJxsQ7Yye35DkWvkdLcvGKqM+x0Ufc=
github.com/gorilla/websocket v1.4.2/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
github.com/gorilla/websocket v1.5.0 h1:PPwGk2jz7EePpoHN/+ClbZu8SPxiqlu12wZP/3sWmnc=
github.com/gorilla/websocket v1.5.0/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
github.com/grokify/html-strip-tags-go v0.0.1 h1:0fThFwLbW7P/kOiTBs03FsJSV9RM2M/Q/MOnCQxKMo0=
github.com/grokify/html-strip-tags-go v0.0.1/go.mod h1:2Su6romC5/1VXOQMaWL2yb618ARB8iVo6/DR99A6d78=
github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU=

2
go.mod
View File

@ -9,7 +9,7 @@ require (
github.com/fsnotify/fsnotify v1.5.1
github.com/go-redis/redis/v8 v8.11.4
github.com/go-sql-driver/mysql v1.6.0
github.com/gorilla/websocket v1.4.2
github.com/gorilla/websocket v1.5.0
github.com/grokify/html-strip-tags-go v0.0.1
github.com/olekukonko/tablewriter v0.0.5
go.opentelemetry.io/otel v1.0.0

4
go.sum
View File

@ -36,8 +36,8 @@ github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.5.6 h1:BKbKCqvP6I+rmFHt06ZmyQtvB8xAkWdhFyr0ZUNZcxQ=
github.com/google/go-cmp v0.5.6/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/gorilla/websocket v1.4.2 h1:+/TMaTYc4QFitKJxsQ7Yye35DkWvkdLcvGKqM+x0Ufc=
github.com/gorilla/websocket v1.4.2/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
github.com/gorilla/websocket v1.5.0 h1:PPwGk2jz7EePpoHN/+ClbZu8SPxiqlu12wZP/3sWmnc=
github.com/gorilla/websocket v1.5.0/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
github.com/grokify/html-strip-tags-go v0.0.1 h1:0fThFwLbW7P/kOiTBs03FsJSV9RM2M/Q/MOnCQxKMo0=
github.com/grokify/html-strip-tags-go v0.0.1/go.mod h1:2Su6romC5/1VXOQMaWL2yb618ARB8iVo6/DR99A6d78=
github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU=

View File

@ -12,11 +12,11 @@ import (
"reflect"
"time"
"github.com/gogf/gf/v2/net/gsvc"
"github.com/gorilla/websocket"
"github.com/gogf/gf/v2/container/gmap"
"github.com/gogf/gf/v2/container/gtype"
"github.com/gogf/gf/v2/net/gsvc"
"github.com/gogf/gf/v2/os/gcache"
"github.com/gogf/gf/v2/os/gsession"
"github.com/gogf/gf/v2/protocol/goai"
@ -31,7 +31,7 @@ type (
servers []*gracefulServer // Underlying http.Server array.
serverCount *gtype.Int // Underlying http.Server count.
closeChan chan struct{} // Used for underlying server closing event notification.
serveTree map[string]interface{} // The route map tree.
serveTree map[string]interface{} // The route maps tree.
serveCache *gcache.Cache // Server caches for internal usage.
routesMap map[string][]registeredRouteItem // Route map mainly for route dumps and repeated route checks.
statusHandlerMap map[string][]HandlerFunc // Custom status handler map.
@ -70,8 +70,8 @@ type (
// handlerFuncInfo contains the HandlerFunc address and its reflection type.
handlerFuncInfo struct {
Func HandlerFunc // Handler function address.
Type reflect.Type // Reflect type information for current handler, which is used for extension of handler feature.
Value reflect.Value // Reflect value information for current handler, which is used for extension of handler feature.
Type reflect.Type // Reflect type information for current handler, which is used for extensions of the handler feature.
Value reflect.Value // Reflect value information for current handler, which is used for extensions of the handler feature.
}
// handlerItem is the registered handler for route handling,
@ -84,7 +84,7 @@ type (
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 hook type.
HookName string // Hook type name, only available for the hook type.
Router *Router // Router object.
Source string // Registering source file `path:line`.
}
@ -141,15 +141,15 @@ const (
)
var (
// methodsMap stores all supported HTTP method,
// it is used for quick HTTP method searching using map.
// methodsMap stores all supported HTTP method.
// It is used for quick HTTP method searching using map.
methodsMap = make(map[string]struct{})
// serverMapping stores more than one server instances for current process.
// serverMapping stores more than one server instances for current processes.
// The key is the name of the server, and the value is its instance.
serverMapping = gmap.NewStrAnyMap(true)
// serverRunning marks the running server count.
// serverRunning marks the running server counts.
// If there is no successful server running or all servers' shutdown, this value is 0.
serverRunning = gtype.NewInt()
@ -160,7 +160,7 @@ var (
return true
},
}
// allDoneChan is the event for all server have done its serving and exit.
// allDoneChan is the event for all servers have done its serving and exit.
// It is used for process blocking purpose.
allDoneChan = make(chan struct{}, 1000)
@ -168,9 +168,9 @@ var (
// The process can only be initialized once.
serverProcessInitialized = gtype.NewBool()
// gracefulEnabled is used for graceful reload feature, which is false in default.
// gracefulEnabled is used for a graceful reload feature, which is false in default.
gracefulEnabled = false
// defaultValueTags is the struct tag names for default value storing.
// defaultValueTags are the struct tag names for default value storing.
defaultValueTags = []string{"d", "default"}
)

View File

@ -15,7 +15,7 @@ import (
// BuildParams builds the request string for the http client. The `params` can be type of:
// string/[]byte/map/struct/*struct.
//
// The optional parameter `noUrlEncode` specifies whether ignore the url encoding for the data.
// The optional parameter `noUrlEncode` specifies whether to ignore the url encoding for the data.
func BuildParams(params interface{}, noUrlEncode ...bool) (encodedParamStr string) {
return httputil.BuildParams(params, noUrlEncode...)
}

View File

@ -14,6 +14,7 @@ import (
"github.com/gogf/gf/v2/internal/intlog"
)
// DefaultHandlerResponse is the default implementation of HandlerResponse.
type DefaultHandlerResponse struct {
Code int `json:"code" dc:"Error code"`
Message string `json:"message" dc:"Error message"`

View File

@ -11,7 +11,6 @@ import (
"fmt"
"io/ioutil"
"github.com/gogf/gf/v2/os/gctx"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/codes"
@ -22,6 +21,7 @@ import (
"github.com/gogf/gf/v2/internal/httputil"
"github.com/gogf/gf/v2/internal/utils"
"github.com/gogf/gf/v2/net/gtrace"
"github.com/gogf/gf/v2/os/gctx"
"github.com/gogf/gf/v2/text/gstr"
"github.com/gogf/gf/v2/util/gconv"
)
@ -73,7 +73,7 @@ func internalMiddlewareServerTracing(r *Request) {
// Inject tracing context.
r.SetCtx(ctx)
// If it is now using default trace provider, it then does no complex tracing jobs.
// If it is now using a default trace provider, it then does no complex tracing jobs.
if gtrace.IsUsingDefaultProvider() {
r.Middleware.Next()
return

View File

@ -32,7 +32,7 @@ type Request struct {
Response *Response // Corresponding Response of this request.
Router *Router // Matched Router for this request. Note that it's not available in HOOK handler.
EnterTime int64 // Request starting time in microseconds.
LeaveTime int64 // Request ending time in microseconds.
LeaveTime int64 // Request to end time in microseconds.
Middleware *middleware // Middleware manager.
StaticFile *staticFile // Static file object for static file serving.
@ -49,10 +49,10 @@ type Request struct {
parsedBody bool // A bool marking whether the request body parsed.
parsedForm bool // A bool marking whether request Form parsed for HTTP method PUT, POST, PATCH.
paramsMap map[string]interface{} // Custom parameters map.
routerMap map[string]string // Router parameters map, which might be nil if there're no router parameters.
routerMap map[string]string // Router parameters map, which might be nil if there are no router parameters.
queryMap map[string]interface{} // Query parameters map, which is nil if there's no query string.
formMap map[string]interface{} // Form parameters map, which is nil if there's no form data from client.
bodyMap map[string]interface{} // Body parameters map, which might be nil if there're no body content.
formMap map[string]interface{} // Form parameters map, which is nil if there's no form of data from the client.
bodyMap map[string]interface{} // Body parameters map, which might be nil if their nobody content.
error error // Current executing error of the request.
exitAll bool // A bool marking whether current request is exited.
parsedHost string // The parsed host name for current host used by GetHost function.

View File

@ -14,7 +14,7 @@ import (
"github.com/gogf/gf/v2/encoding/gbase64"
)
// BasicAuth enables the http basic authentication feature with given passport and password
// 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 (r *Request) BasicAuth(user, pass string, tips ...string) bool {

View File

@ -29,7 +29,7 @@ func (m *middleware) Next() {
var item *handlerParsedItem
var loop = true
for loop {
// Check whether the request is exited.
// Check whether the request is excited.
if m.request.IsExited() || m.handlerIndex >= len(m.request.handlers) {
break
}
@ -112,7 +112,7 @@ func (m *middleware) Next() {
loop = false
})
}
// Check the http status code after all handler and middleware done.
// Check the http status code after all handlers and middleware done.
if m.request.IsExited() || m.handlerIndex >= len(m.request.handlers) {
if m.request.Response.Status == 0 {
if m.request.Middleware.served {

View File

@ -320,7 +320,7 @@ func (r *Request) parseForm() {
}
}
// GetMultipartForm parses and returns the form as multipart form.
// GetMultipartForm parses and returns the form as multipart forms.
func (r *Request) GetMultipartForm() *multipart.Form {
r.parseForm()
return r.MultipartForm

View File

@ -48,7 +48,7 @@ func (r *Request) SetCtx(ctx context.Context) {
r.context = ctx
}
// GetCtxVar retrieves and returns a Var with given key name.
// 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 (r *Request) GetCtxVar(key interface{}, def ...interface{}) *gvar.Var {
@ -59,7 +59,7 @@ func (r *Request) GetCtxVar(key interface{}, def ...interface{}) *gvar.Var {
return gvar.New(value)
}
// SetCtxVar sets custom parameter to context with key-value pair.
// SetCtxVar sets custom parameter to context with key-value pairs.
func (r *Request) SetCtxVar(key interface{}, value interface{}) {
r.context = context.WithValue(r.Context(), key, value)
}

View File

@ -27,7 +27,7 @@ type UploadFile struct {
ctx context.Context
}
// UploadFiles is array type for *UploadFile.
// UploadFiles is an array type of *UploadFile.
type UploadFiles []*UploadFile
// Save saves the single uploading file to directory path and returns the saved file name.

View File

@ -11,7 +11,7 @@ import (
"github.com/gogf/gf/v2/util/gconv"
)
// SetForm sets custom form value with key-value pair.
// SetForm sets custom form value with key-value pairs.
func (r *Request) SetForm(key string, value interface{}) {
r.parseForm()
if r.formMap == nil {

View File

@ -15,7 +15,7 @@ import (
)
// GetPage creates and returns the pagination object for given `totalSize` and `pageSize`.
// NOTE THAT the page parameter name from client is constantly defined as gpage.DefaultPageName
// NOTE THAT the page parameter name from clients is constantly defined as gpage.DefaultPageName
// for simplification and convenience.
func (r *Request) GetPage(totalSize, pageSize int) *gpage.Page {
// It must have Router object attribute.

View File

@ -8,7 +8,7 @@ package ghttp
import "github.com/gogf/gf/v2/container/gvar"
// SetParam sets custom parameter with key-value pair.
// SetParam sets custom parameter with key-value pairs.
func (r *Request) SetParam(key string, value interface{}) {
if r.paramsMap == nil {
r.paramsMap = make(map[string]interface{})
@ -16,7 +16,7 @@ func (r *Request) SetParam(key string, value interface{}) {
r.paramsMap[key] = value
}
// SetParamMap sets custom parameter with key-value pair map.
// SetParamMap sets custom parameter with key-value pair maps.
func (r *Request) SetParamMap(data map[string]interface{}) {
if r.paramsMap == nil {
r.paramsMap = make(map[string]interface{})
@ -26,7 +26,7 @@ func (r *Request) SetParamMap(data map[string]interface{}) {
}
}
// GetParam returns custom parameter with given name `key`.
// 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 (r *Request) GetParam(key string, def ...interface{}) *gvar.Var {

View File

@ -11,7 +11,7 @@ import (
"github.com/gogf/gf/v2/util/gconv"
)
// SetQuery sets custom query value with key-value pair.
// SetQuery sets custom query value with key-value pairs.
func (r *Request) SetQuery(key string, value interface{}) {
r.parseQuery()
if r.queryMap == nil {
@ -20,7 +20,7 @@ func (r *Request) SetQuery(key string, value interface{}) {
r.queryMap[key] = value
}
// GetQuery retrieves and returns parameter with given name `key` from query string
// 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.
//
@ -47,8 +47,8 @@ func (r *Request) GetQuery(key string, def ...interface{}) *gvar.Var {
return nil
}
// GetQueryMap retrieves and returns all parameters passed from client using HTTP GET method
// as map. The parameter `kvMap` specifies the keys retrieving from client parameters,
// 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
@ -94,8 +94,8 @@ func (r *Request) GetQueryMap(kvMap ...map[string]interface{}) map[string]interf
return m
}
// GetQueryMapStrStr retrieves and returns all parameters passed from client using HTTP GET method
// as map[string]string. The parameter `kvMap` specifies the keys
// 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 (r *Request) GetQueryMapStrStr(kvMap ...map[string]interface{}) map[string]string {
@ -110,7 +110,7 @@ func (r *Request) GetQueryMapStrStr(kvMap ...map[string]interface{}) map[string]
return nil
}
// GetQueryMapStrVar retrieves and returns all parameters passed from client using HTTP GET method
// 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.
@ -126,8 +126,8 @@ func (r *Request) GetQueryMapStrVar(kvMap ...map[string]interface{}) map[string]
return nil
}
// GetQueryStruct retrieves all parameters passed from client using HTTP GET method
// and converts them to given struct object. Note that the parameter `pointer` is a pointer
// 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 (r *Request) GetQueryStruct(pointer interface{}, mapping ...map[string]string) error {

View File

@ -14,7 +14,7 @@ import (
"github.com/gogf/gf/v2/util/gutil"
)
// GetRequest retrieves and returns the parameter named `key` passed from client and
// 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.
//
@ -50,8 +50,8 @@ func (r *Request) GetRequest(key string, def ...interface{}) *gvar.Var {
return nil
}
// GetRequestMap retrieves and returns all parameters passed from client and custom params
// as map, no matter what HTTP method the client is using. The parameter `kvMap` specifies
// 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.
//
@ -131,7 +131,7 @@ func (r *Request) GetRequestMap(kvMap ...map[string]interface{}) map[string]inte
return m
}
// GetRequestMapStrStr retrieves and returns all parameters passed from client and custom
// 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.
@ -147,7 +147,7 @@ func (r *Request) GetRequestMapStrStr(kvMap ...map[string]interface{}) map[strin
return nil
}
// GetRequestMapStrVar retrieves and returns all parameters passed from client and custom
// 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.
@ -163,8 +163,8 @@ func (r *Request) GetRequestMapStrVar(kvMap ...map[string]interface{}) map[strin
return nil
}
// GetRequestStruct retrieves all parameters passed from client and custom params no matter
// what HTTP method the client is using, and converts them to given struct object. Note that
// 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 (r *Request) GetRequestStruct(pointer interface{}, mapping ...map[string]string) error {

View File

@ -8,7 +8,7 @@ package ghttp
import "github.com/gogf/gf/v2/container/gvar"
// GetRouterMap retrieves and returns a copy of router map.
// GetRouterMap retrieves and returns a copy of the router map.
func (r *Request) GetRouterMap() map[string]string {
if r.routerMap != nil {
m := make(map[string]string, len(r.routerMap))

View File

@ -96,7 +96,7 @@ func (r *Response) ServeFileDownload(path string, name ...string) {
r.Server.serveFile(r.Request, serveFile)
}
// RedirectTo redirects client to another location.
// 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 (r *Response) RedirectTo(location string, code ...int) {
@ -109,7 +109,7 @@ func (r *Response) RedirectTo(location string, code ...int) {
r.Request.Exit()
}
// RedirectBack redirects client back to referer.
// 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 (r *Response) RedirectBack(code ...int) {

View File

@ -31,7 +31,7 @@ type CORSOptions struct {
var (
// defaultAllowHeaders is the default allowed headers for CORS.
// It's defined another map for better header key searching performance.
// It defined another map for better header key searching performance.
defaultAllowHeaders = "Origin,Content-Type,Accept,User-Agent,Cookie,Authorization,X-Auth-Token,X-Requested-With"
defaultAllowHeadersMap = make(map[string]struct{})
)

View File

@ -93,7 +93,7 @@ func (r *Response) buildInVars(params ...map[string]interface{}) map[string]inte
"Cookie": r.Request.Cookie.Map(),
"Session": sessionMap,
})
// Note that it should assign no Config variable to template
// Note that it should assign no Config variable to a template
// if there's no configuration file.
if v, _ := gcfg.Instance().Data(r.Request.Context()); len(v) > 0 {
m["Config"] = v

View File

@ -37,7 +37,7 @@ func (r *Response) Write(content ...interface{}) {
}
// WriteExit writes `content` to the response buffer and exits executing of current handler.
// The "Exit" feature is commonly used to replace usage of return statement in the handler,
// The "Exit" feature is commonly used to replace usage of return statements in the handler,
// for convenience.
func (r *Response) WriteExit(content ...interface{}) {
r.Write(content...)
@ -52,7 +52,7 @@ func (r *Response) WriteOver(content ...interface{}) {
// WriteOverExit overwrites the response buffer with `content` and exits executing
// of current handler. The "Exit" feature is commonly used to replace usage of return
// statement in the handler, for convenience.
// statements in the handler, for convenience.
func (r *Response) WriteOverExit(content ...interface{}) {
r.WriteOver(content...)
r.Request.Exit()
@ -64,7 +64,7 @@ func (r *Response) Writef(format string, params ...interface{}) {
}
// WritefExit writes the response with fmt.Sprintf and exits executing of current handler.
// The "Exit" feature is commonly used to replace usage of return statement in the handler,
// The "Exit" feature is commonly used to replace usage of return statements in the handler,
// for convenience.
func (r *Response) WritefExit(format string, params ...interface{}) {
r.Writef(format, params...)
@ -82,7 +82,7 @@ func (r *Response) Writeln(content ...interface{}) {
// WritelnExit writes the response with `content` and new line and exits executing
// of current handler. The "Exit" feature is commonly used to replace usage of return
// statement in the handler, for convenience.
// statements in the handler, for convenience.
func (r *Response) WritelnExit(content ...interface{}) {
r.Writeln(content...)
r.Request.Exit()
@ -104,7 +104,7 @@ func (r *Response) WriteflnExit(format string, params ...interface{}) {
// WriteJson writes `content` to the response with JSON format.
func (r *Response) WriteJson(content interface{}) error {
r.Header().Set("Content-Type", contentTypeJson)
// If given string/[]byte, response it directly to client.
// If given string/[]byte, response it directly to the client.
switch content.(type) {
case string, []byte:
r.Write(gconv.String(content))
@ -121,7 +121,7 @@ func (r *Response) WriteJson(content interface{}) error {
// WriteJsonExit writes `content` to the response with JSON format and exits executing
// of current handler if success. The "Exit" feature is commonly used to replace usage of
// return statement in the handler, for convenience.
// return statements in the handler, for convenience.
func (r *Response) WriteJsonExit(content interface{}) error {
if err := r.WriteJson(content); err != nil {
return err
@ -161,7 +161,7 @@ func (r *Response) WriteJsonP(content interface{}) error {
// WriteJsonPExit writes `content` to the response with JSONP format and exits executing
// of current handler if success. The "Exit" feature is commonly used to replace usage of
// return statement in the handler, for convenience.
// return statements in the handler, for convenience.
//
// Note that there should be a "callback" parameter in the request for JSONP format.
func (r *Response) WriteJsonPExit(content interface{}) error {
@ -175,7 +175,7 @@ func (r *Response) WriteJsonPExit(content interface{}) error {
// WriteXml writes `content` to the response with XML format.
func (r *Response) WriteXml(content interface{}, rootTag ...string) error {
r.Header().Set("Content-Type", contentTypeXml)
// If given string/[]byte, response it directly to client.
// If given string/[]byte, response it directly to clients.
switch content.(type) {
case string, []byte:
r.Write(gconv.String(content))
@ -191,7 +191,7 @@ func (r *Response) WriteXml(content interface{}, rootTag ...string) error {
// WriteXmlExit writes `content` to the response with XML format and exits executing
// of current handler if success. The "Exit" feature is commonly used to replace usage
// of return statement in the handler, for convenience.
// of return statements in the handler, for convenience.
func (r *Response) WriteXmlExit(content interface{}, rootTag ...string) error {
if err := r.WriteXml(content, rootTag...); err != nil {
return err
@ -201,7 +201,7 @@ func (r *Response) WriteXmlExit(content interface{}, rootTag ...string) error {
}
// WriteStatus writes HTTP `status` and `content` to the response.
// Note that do not set Content-Type header here.
// Note that it does not set a Content-Type header here.
func (r *Response) WriteStatus(status int, content ...interface{}) {
r.WriteHeader(status)
if len(content) > 0 {
@ -213,7 +213,7 @@ func (r *Response) WriteStatus(status int, content ...interface{}) {
// WriteStatusExit writes HTTP `status` and `content` to the response and exits executing
// of current handler if success. The "Exit" feature is commonly used to replace usage of
// return statement in the handler, for convenience.
// return statements in the handler, for convenience.
func (r *Response) WriteStatusExit(status int, content ...interface{}) {
r.WriteStatus(status, content...)
r.Request.Exit()

View File

@ -50,7 +50,7 @@ func (w *ResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {
return w.writer.(http.Hijacker).Hijack()
}
// Flush outputs the buffer to client and clears the buffer.
// Flush outputs the buffer to clients and clears the buffer.
func (w *ResponseWriter) Flush() {
if w.hijacked {
return

View File

@ -16,7 +16,6 @@ import (
"strings"
"time"
"github.com/gogf/gf/v2/net/ghttp/internal/swaggerui"
"github.com/olekukonko/tablewriter"
"github.com/gogf/gf/v2/container/garray"
@ -25,6 +24,7 @@ import (
"github.com/gogf/gf/v2/errors/gcode"
"github.com/gogf/gf/v2/errors/gerror"
"github.com/gogf/gf/v2/internal/intlog"
"github.com/gogf/gf/v2/net/ghttp/internal/swaggerui"
"github.com/gogf/gf/v2/os/gcache"
"github.com/gogf/gf/v2/os/genv"
"github.com/gogf/gf/v2/os/gfile"
@ -39,7 +39,7 @@ import (
)
func init() {
// Initialize the methods map.
// Initialize the method map.
for _, v := range strings.Split(supportedHttpMethods, ",") {
methodsMap[v] = struct{}{}
}
@ -51,7 +51,7 @@ func serverProcessInit() {
if !serverProcessInitialized.Cas(false, true) {
return
}
// This means it is a restart server, it should kill its parent before starting its listening,
// This means it is a restart server. It should kill its parent before starting its listening,
// to avoid duplicated port listening in two processes.
if !genv.Get(adminActionRestartEnvKey).IsEmpty() {
if p, err := os.FindProcess(gproc.PPid()); err == nil {
@ -70,7 +70,7 @@ func serverProcessInit() {
go handleProcessSignal()
// Process message handler.
// It's enabled only graceful feature is enabled.
// It enabled only a graceful feature is enabled.
if gracefulEnabled {
intlog.Printf(ctx, "%d: graceful reload feature is enabled", gproc.Pid())
go handleProcessMessage()
@ -80,7 +80,7 @@ func serverProcessInit() {
// It's an ugly calling for better initializing the main package path
// in source development environment. It is useful only be used in main goroutine.
// It fails retrieving the main package path in asynchronous goroutines.
// It fails to retrieve the main package path in asynchronous goroutines.
gfile.MainPkgPath()
}
@ -213,7 +213,7 @@ func (s *Server) Start() error {
// Check the group routes again.
s.handlePreBindItems(ctx)
// If there's no route registered and no static service enabled,
// If there's no route registered and no static service enabled,
// it then returns an error of invalid usage of server.
if len(s.routesMap) == 0 && !s.config.FileServerEnabled {
return gerror.NewCode(
@ -525,8 +525,8 @@ func (s *Server) startServer(fdMap listenerFdMap) {
)
if len(addrAndFd) > 1 {
itemFunc = addrAndFd[0]
// The Windows OS does not support socket file descriptor passing
// from parent process.
// The Window OS does not support socket file descriptor passing
// from the parent process.
if runtime.GOOS != "windows" {
fd = gconv.Int(addrAndFd[1])
}

View File

@ -196,7 +196,7 @@ func bufferToServerFdMap(buffer []byte) map[string]listenerFdMap {
sfm := make(map[string]listenerFdMap)
if len(buffer) > 0 {
j, _ := gjson.LoadContent(buffer)
for k, _ := range j.Var().Map() {
for k := range j.Var().Map() {
m := make(map[string]string)
for k, v := range j.Get(k).Map() {
m[k] = gconv.String(v)

View File

@ -18,10 +18,10 @@ import (
"github.com/gogf/gf/v2/internal/intlog"
)
// procSignalChan is the channel for listening the signal.
// procSignalChan is the channel for listening to the signal.
var procSignalChan = make(chan os.Signal)
// handleProcessSignal handles all signal from system.
// handleProcessSignal handles all signals from system.
func handleProcessSignal() {
var (
ctx = context.TODO()

View File

@ -9,7 +9,7 @@
package ghttp
// registerSignalHandler does nothing on windows platform.
// registerSignalHandler does nothing on a window platform.
func handleProcessSignal() {
}

View File

@ -28,10 +28,10 @@ import (
const (
defaultHttpAddr = ":80" // Default listening port for HTTP.
defaultHttpsAddr = ":443" // Default listening port for HTTPS.
UriTypeDefault = 0 // Method names to URI converting type, which converts name to its lower case and joins the words using char '-'.
UriTypeFullName = 1 // Method names to URI converting type, which does no converting to the method name.
UriTypeAllLower = 2 // Method names to URI converting type, which converts name to its lower case.
UriTypeCamel = 3 // Method names to URI converting type, which converts name to its camel case.
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.
)
// ServerConfig is the HTTP Server configuration manager.

View File

@ -26,7 +26,7 @@ func (s *Server) SetCookieDomain(domain string) {
s.config.CookieDomain = domain
}
// GetCookieMaxAge returns the CookieMaxAge of server.
// GetCookieMaxAge returns the CookieMaxAge of the server.
func (s *Server) GetCookieMaxAge() time.Duration {
return s.config.CookieMaxAge
}

View File

@ -11,7 +11,7 @@ func (s *Server) SetRewrite(uri string, rewrite string) {
s.config.Rewrites[uri] = rewrite
}
// SetRewriteMap sets the rewrite map for server.
// SetRewriteMap sets the rewritten map for server.
func (s *Server) SetRewriteMap(rewrites map[string]string) {
for k, v := range rewrites {
s.config.Rewrites[k] = v

View File

@ -12,10 +12,9 @@ import (
"context"
"strings"
"github.com/gogf/gf/v2/os/gres"
"github.com/gogf/gf/v2/container/garray"
"github.com/gogf/gf/v2/os/gfile"
"github.com/gogf/gf/v2/os/gres"
"github.com/gogf/gf/v2/util/gconv"
)
@ -30,7 +29,7 @@ func (s *Server) SetIndexFiles(indexFiles []string) {
s.config.IndexFiles = indexFiles
}
// GetIndexFiles retrieves and returns the index files from server.
// GetIndexFiles retrieves and returns the index files from the server.
func (s *Server) GetIndexFiles() []string {
return s.config.IndexFiles
}

View File

@ -31,7 +31,7 @@ type CookieOptions struct {
// cookieItem is the item stored in Cookie.
type cookieItem struct {
*http.Cookie // Underlying cookie items.
FromClient bool // Mark this cookie received from client.
FromClient bool // Mark this cookie received from the client.
}
// GetCookie creates or retrieves a cookie object with given request.
@ -47,7 +47,7 @@ func GetCookie(r *Request) *Cookie {
}
}
// init does lazy initialization for cookie object.
// init does lazy initialization for the cookie object.
func (c *Cookie) init() {
if c.data != nil {
return
@ -76,7 +76,7 @@ func (c *Cookie) Map() map[string]string {
return m
}
// Contains checks if given key exists and not expired in cookie.
// Contains checks if given key exists and not expire in cookie.
func (c *Cookie) Contains(key string) bool {
c.init()
if r, ok := c.data[key]; ok {
@ -191,7 +191,7 @@ func (c *Cookie) RemoveCookie(key, domain, path string) {
c.SetCookie(key, "", domain, path, -24*time.Hour)
}
// Flush outputs the cookie items to client.
// Flush outputs the cookie items to the client.
func (c *Cookie) Flush() {
if len(c.data) == 0 {
return

View File

@ -29,14 +29,15 @@ func (s *Server) Domain(domains string) *Domain {
return d
}
// BindHandler binds the handler for the specified pattern.
func (d *Domain) BindHandler(pattern string, handler interface{}) {
for domain, _ := range d.domains {
for domain := range d.domains {
d.server.BindHandler(pattern+"@"+domain, handler)
}
}
func (d *Domain) doBindHandler(ctx context.Context, in doBindHandlerInput) {
for domain, _ := range d.domains {
for domain := range d.domains {
d.server.doBindHandler(ctx, doBindHandlerInput{
Prefix: in.Prefix,
Pattern: in.Pattern + "@" + domain,
@ -47,14 +48,15 @@ func (d *Domain) doBindHandler(ctx context.Context, in doBindHandlerInput) {
}
}
// BindObject binds the object for the specified pattern.
func (d *Domain) BindObject(pattern string, obj interface{}, methods ...string) {
for domain, _ := range d.domains {
for domain := range d.domains {
d.server.BindObject(pattern+"@"+domain, obj, methods...)
}
}
func (d *Domain) doBindObject(ctx context.Context, in doBindObjectInput) {
for domain, _ := range d.domains {
for domain := range d.domains {
d.server.doBindObject(ctx, doBindObjectInput{
Prefix: in.Prefix,
Pattern: in.Pattern + "@" + domain,
@ -66,14 +68,15 @@ func (d *Domain) doBindObject(ctx context.Context, in doBindObjectInput) {
}
}
// BindObjectMethod binds the method for the specified pattern.
func (d *Domain) BindObjectMethod(pattern string, obj interface{}, method string) {
for domain, _ := range d.domains {
for domain := range d.domains {
d.server.BindObjectMethod(pattern+"@"+domain, obj, method)
}
}
func (d *Domain) doBindObjectMethod(ctx context.Context, in doBindObjectMethodInput) {
for domain, _ := range d.domains {
for domain := range d.domains {
d.server.doBindObjectMethod(ctx, doBindObjectMethodInput{
Prefix: in.Prefix,
Pattern: in.Pattern + "@" + domain,
@ -85,14 +88,15 @@ func (d *Domain) doBindObjectMethod(ctx context.Context, in doBindObjectMethodIn
}
}
// BindObjectRest binds the RESTful API for the specified pattern.
func (d *Domain) BindObjectRest(pattern string, obj interface{}) {
for domain, _ := range d.domains {
for domain := range d.domains {
d.server.BindObjectRest(pattern+"@"+domain, obj)
}
}
func (d *Domain) doBindObjectRest(ctx context.Context, in doBindObjectInput) {
for domain, _ := range d.domains {
for domain := range d.domains {
d.server.doBindObjectRest(ctx, doBindObjectInput{
Prefix: in.Prefix,
Pattern: in.Pattern + "@" + domain,
@ -104,14 +108,15 @@ func (d *Domain) doBindObjectRest(ctx context.Context, in doBindObjectInput) {
}
}
// BindHookHandler binds the hook handler for the specified pattern.
func (d *Domain) BindHookHandler(pattern string, hook string, handler HandlerFunc) {
for domain, _ := range d.domains {
for domain := range d.domains {
d.server.BindHookHandler(pattern+"@"+domain, hook, handler)
}
}
func (d *Domain) doBindHookHandler(ctx context.Context, in doBindHookHandlerInput) {
for domain, _ := range d.domains {
for domain := range d.domains {
d.server.doBindHookHandler(ctx, doBindHookHandlerInput{
Prefix: in.Prefix,
Pattern: in.Pattern + "@" + domain,
@ -122,36 +127,42 @@ func (d *Domain) doBindHookHandler(ctx context.Context, in doBindHookHandlerInpu
}
}
func (d *Domain) BindHookHandlerByMap(pattern string, hookmap map[string]HandlerFunc) {
for domain, _ := range d.domains {
d.server.BindHookHandlerByMap(pattern+"@"+domain, hookmap)
// BindHookHandlerByMap binds the hook handler for the specified pattern.
func (d *Domain) BindHookHandlerByMap(pattern string, hookMap map[string]HandlerFunc) {
for domain := range d.domains {
d.server.BindHookHandlerByMap(pattern+"@"+domain, hookMap)
}
}
// BindStatusHandler binds the status handler for the specified pattern.
func (d *Domain) BindStatusHandler(status int, handler HandlerFunc) {
for domain, _ := range d.domains {
for domain := range d.domains {
d.server.addStatusHandler(d.server.statusHandlerKey(status, domain), handler)
}
}
// BindStatusHandlerByMap binds the status handler for the specified pattern.
func (d *Domain) BindStatusHandlerByMap(handlerMap map[int]HandlerFunc) {
for k, v := range handlerMap {
d.BindStatusHandler(k, v)
}
}
// BindMiddleware binds the middleware for the specified pattern.
func (d *Domain) BindMiddleware(pattern string, handlers ...HandlerFunc) {
for domain, _ := range d.domains {
for domain := range d.domains {
d.server.BindMiddleware(pattern+"@"+domain, handlers...)
}
}
// BindMiddlewareDefault binds the default middleware for the specified pattern.
func (d *Domain) BindMiddlewareDefault(handlers ...HandlerFunc) {
for domain, _ := range d.domains {
for domain := range d.domains {
d.server.BindMiddleware(defaultMiddlewarePattern+"@"+domain, handlers...)
}
}
// Use adds middleware to the domain.
func (d *Domain) Use(handlers ...HandlerFunc) {
d.BindMiddlewareDefault(handlers...)
}

View File

@ -24,7 +24,7 @@ import (
// gracefulServer wraps the net/http.Server with graceful reload/restart feature.
type gracefulServer struct {
server *Server // Belonged server.
fd uintptr // File descriptor for passing to child process when graceful reload.
fd uintptr // File descriptor for passing to the child process when graceful reload.
address string // Listening address like:":80", ":8080".
httpServer *http.Server // Underlying http.Server.
rawListener net.Listener // Underlying net.Listener.
@ -34,7 +34,7 @@ type gracefulServer struct {
status int // Status of current server.
}
// newGracefulServer creates and returns a graceful http server with given address.
// newGracefulServer creates and returns a graceful http server with a given address.
// The optional parameter `fd` specifies the file descriptor which is passed from parent server.
func (s *Server) newGracefulServer(address string, fd ...int) *gracefulServer {
// Change port to address like: 80 -> :80
@ -52,7 +52,7 @@ func (s *Server) newGracefulServer(address string, fd ...int) *gracefulServer {
return gs
}
// newGracefulServer creates and returns an underlying http.Server with given address.
// newHttpServer creates and returns an underlying http.Server with a given address.
func (s *Server) newHttpServer(address string) *http.Server {
server := &http.Server{
Addr: address,
@ -78,8 +78,8 @@ func (s *gracefulServer) ListenAndServe() error {
return s.doServe(context.TODO())
}
// Fd retrieves and returns the file descriptor of current server.
// It is available ony in *nix like operating systems like: linux, unix, darwin.
// Fd retrieves and returns the file descriptor of the current server.
// It is available ony in *nix like operating systems like linux, unix, darwin.
func (s *gracefulServer) Fd() uintptr {
if ln := s.getRawListener(); ln != nil {
file, err := ln.(*net.TCPListener).File()
@ -139,7 +139,7 @@ func (s *gracefulServer) ListenAndServeTLS(certFile, keyFile string, tlsConfig .
return s.doServe(ctx)
}
// GetListenedPort retrieves and returns one port which is listened by current server.
// GetListenedPort retrieves and returns one port which is listened to by current server.
func (s *gracefulServer) GetListenedPort() int {
if ln := s.getRawListener(); ln != nil {
return ln.Addr().(*net.TCPAddr).Port

View File

@ -27,7 +27,7 @@ import (
// 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 make serve implementing the interface of http.Handler.
// This function also makes serve implementing the interface of http.Handler.
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// Max body size limit.
if s.config.ClientMaxBodySize > 0 {
@ -174,9 +174,9 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
request.Session.MustId() != request.GetSessionId() {
request.Cookie.SetSessionId(request.Session.MustId())
}
// Output the cookie content to client.
// Output the cookie content to the client.
request.Cookie.Flush()
// Output the buffer content to client.
// Output the buffer content to the client.
request.Response.Flush()
// HOOK - AfterOutput
if !request.IsExited() {
@ -248,8 +248,8 @@ func (s *Server) searchStaticFile(uri string) *staticFile {
return nil
}
// serveFile serves the static file for client.
// The optional parameter `allowIndex` specifies if allowing directory listing if `f` is directory.
// serveFile serves the static file for the client.
// The optional parameter `allowIndex` specifies if allowing directory listing if `f` is a directory.
func (s *Server) serveFile(r *Request, f *staticFile, allowIndex ...bool) {
// Use resource file from memory.
if f.File != nil {
@ -291,7 +291,7 @@ func (s *Server) serveFile(r *Request, f *staticFile, allowIndex ...bool) {
}
}
// listDir lists the sub files of specified directory as HTML content to client.
// listDir lists the sub files of specified directory as HTML content to the client.
func (s *Server) listDir(r *Request, f http.File) {
files, err := f.Readdir(-1)
if err != nil {

View File

@ -12,11 +12,11 @@ type Plugin interface {
Author() string // Author returns the author of the plugin.
Version() string // Version returns the version of the plugin, like "v1.0.0".
Description() string // Description returns the description of the plugin.
Install(s *Server) error // Install installs the plugin before server starts.
Install(s *Server) error // Install installs the plugin before the server starts.
Remove() error // Remove removes the plugin.
}
// Plugin adds plugin to server.
// Plugin adds plugin to the server.
func (s *Server) Plugin(plugin ...Plugin) {
s.plugins = append(s.plugins, plugin...)
}

View File

@ -34,7 +34,7 @@ var (
handlerIdGenerator = gtype.NewInt()
)
// routerMapKey creates and returns an unique router key for given parameters.
// routerMapKey creates and returns a unique router key for given parameters.
// This key is used for Server.routerMap attribute, which is mainly for checks for
// repeated router registering.
func (s *Server) routerMapKey(hook, method, path, domain string) string {
@ -73,8 +73,8 @@ type setHandlerInput struct {
HandlerItem *handlerItem
}
// setHandler creates router item with given handler and pattern and registers the handler to the router tree.
// The router tree can be treated as a multilayer hash table, please refer to the comment in following codes.
// setHandler creates router item with a given handler and pattern and registers the handler to the router tree.
// The router tree can be treated as a multilayer hash table, please refer to the comment in the following codes.
// This function is called during server starts up, which cares little about the performance. What really cares
// is the well-designed router storage structure for router searching when the request is under serving.
func (s *Server) setHandler(ctx context.Context, in setHandlerInput) {
@ -97,7 +97,7 @@ func (s *Server) setHandler(ctx context.Context, in setHandlerInput) {
return
}
// Change the registered route according meta info from its request structure.
// Change the registered route according to meta info from its request structure.
if handler.Info.Type != nil && handler.Info.Type.NumIn() == 2 {
var objectReq = reflect.New(handler.Info.Type.In(1))
if v := gmeta.Get(objectReq, goai.TagNamePath); !v.IsEmpty() {
@ -201,7 +201,7 @@ func (s *Server) setHandler(ctx context.Context, in setHandlerInput) {
lists = append(lists, v.(*glist.List))
}
}
// Make a new bucket for current node.
// Make a new bucket for the current node.
if _, ok := p.(map[string]interface{})[part]; !ok {
p.(map[string]interface{})[part] = make(map[string]interface{})
}
@ -270,7 +270,7 @@ func (s *Server) setHandler(ctx context.Context, in setHandlerInput) {
// 2. URI: The deeper, the higher (simply check the count of char '/' in the URI).
// 3. Route type: {xxx} > :xxx > *xxx.
func (s *Server) compareRouterPriority(newItem *handlerItem, oldItem *handlerItem) bool {
// If they're all type of middleware, the priority is according their registered sequence.
// If they're all types of middleware, the priority is according to their registered sequence.
if newItem.Type == HandlerTypeMiddleware && oldItem.Type == HandlerTypeMiddleware {
return false
}
@ -348,7 +348,7 @@ func (s *Server) compareRouterPriority(newItem *handlerItem, oldItem *handlerIte
return false
}
// If the counts of their fuzzy rules equal.
// If the counts of their fuzzy rules are equal.
// Eg: /name/{act} > /name/:act
if fuzzyCountFieldNew > fuzzyCountFieldOld {
@ -385,7 +385,7 @@ func (s *Server) compareRouterPriority(newItem *handlerItem, oldItem *handlerIte
return false
}
// patternToRegular converts route rule to according regular expression.
// patternToRegular converts route rule to according to regular expression.
func (s *Server) patternToRegular(rule string) (regular string, names []string) {
if len(rule) < 2 {
return rule, nil

View File

@ -36,8 +36,8 @@ type (
pattern string
object interface{} // Can be handler, controller or object.
params []interface{} // Extra parameters for route registering depending on the type.
source string // Handler is register at certain source file path:line.
bound bool // Is this item bound to server.
source string // Handler is a register at a certain source file path: line.
bound bool // Is this item bound to server?
}
)
@ -114,7 +114,7 @@ func (d *Domain) Group(prefix string, groups ...func(group *RouterGroup)) *Route
return routerGroup
}
// Group creates and returns a sub-group of current router group.
// Group creates and returns a subgroup of the current router group.
func (g *RouterGroup) Group(prefix string, groups ...func(group *RouterGroup)) *RouterGroup {
if prefix == "/" {
prefix = ""
@ -137,7 +137,7 @@ func (g *RouterGroup) Group(prefix string, groups ...func(group *RouterGroup)) *
return group
}
// Clone returns a new router group which is a clone of current group.
// Clone returns a new router group which is a clone of the current group.
func (g *RouterGroup) Clone() *RouterGroup {
newGroup := &RouterGroup{
parent: g.parent,
@ -150,7 +150,7 @@ func (g *RouterGroup) Clone() *RouterGroup {
return newGroup
}
// Bind does batch route registering feature for router group.
// Bind does batch route registering feature for a router group.
func (g *RouterGroup) Bind(handlerOrObject ...interface{}) *RouterGroup {
var (
ctx = context.TODO()
@ -176,7 +176,7 @@ func (g *RouterGroup) Bind(handlerOrObject ...interface{}) *RouterGroup {
return group
}
// ALL registers a http handler to given route pattern and all http methods.
// ALL register a http handler to give the route pattern and all http methods.
func (g *RouterGroup) ALL(pattern string, object interface{}, params ...interface{}) *RouterGroup {
return g.Clone().preBindToLocalArray(
groupBindTypeHandler,
@ -200,52 +200,52 @@ func (g *RouterGroup) Map(m map[string]interface{}) {
}
}
// GET registers a http handler to given route pattern and http method: GET.
// GET registers a http handler to give the route pattern and the http method: GET.
func (g *RouterGroup) GET(pattern string, object interface{}, params ...interface{}) *RouterGroup {
return g.Clone().preBindToLocalArray(groupBindTypeHandler, "GET:"+pattern, object, params...)
}
// PUT registers a http handler to given route pattern and http method: PUT.
// PUT registers a http handler to give the route pattern and the http method: PUT.
func (g *RouterGroup) PUT(pattern string, object interface{}, params ...interface{}) *RouterGroup {
return g.Clone().preBindToLocalArray(groupBindTypeHandler, "PUT:"+pattern, object, params...)
}
// POST registers a http handler to given route pattern and http method: POST.
// POST registers a http handler to give the route pattern and the http method: POST.
func (g *RouterGroup) POST(pattern string, object interface{}, params ...interface{}) *RouterGroup {
return g.Clone().preBindToLocalArray(groupBindTypeHandler, "POST:"+pattern, object, params...)
}
// DELETE registers a http handler to given route pattern and http method: DELETE.
// DELETE registers a http handler to give the route pattern and the http method: DELETE.
func (g *RouterGroup) DELETE(pattern string, object interface{}, params ...interface{}) *RouterGroup {
return g.Clone().preBindToLocalArray(groupBindTypeHandler, "DELETE:"+pattern, object, params...)
}
// PATCH registers a http handler to given route pattern and http method: PATCH.
// PATCH registers a http handler to give the route pattern and the http method: PATCH.
func (g *RouterGroup) PATCH(pattern string, object interface{}, params ...interface{}) *RouterGroup {
return g.Clone().preBindToLocalArray(groupBindTypeHandler, "PATCH:"+pattern, object, params...)
}
// HEAD registers a http handler to given route pattern and http method: HEAD.
// HEAD registers a http handler to give the route pattern and the http method: HEAD.
func (g *RouterGroup) HEAD(pattern string, object interface{}, params ...interface{}) *RouterGroup {
return g.Clone().preBindToLocalArray(groupBindTypeHandler, "HEAD:"+pattern, object, params...)
}
// CONNECT registers a http handler to given route pattern and http method: CONNECT.
// CONNECT registers a http handler to give the route pattern and the http method: CONNECT.
func (g *RouterGroup) CONNECT(pattern string, object interface{}, params ...interface{}) *RouterGroup {
return g.Clone().preBindToLocalArray(groupBindTypeHandler, "CONNECT:"+pattern, object, params...)
}
// OPTIONS registers a http handler to given route pattern and http method: OPTIONS.
// OPTIONS register a http handler to give the route pattern and the http method: OPTIONS.
func (g *RouterGroup) OPTIONS(pattern string, object interface{}, params ...interface{}) *RouterGroup {
return g.Clone().preBindToLocalArray(groupBindTypeHandler, "OPTIONS:"+pattern, object, params...)
}
// TRACE registers a http handler to given route pattern and http method: TRACE.
// TRACE registers a http handler to give the route pattern and the http method: TRACE.
func (g *RouterGroup) TRACE(pattern string, object interface{}, params ...interface{}) *RouterGroup {
return g.Clone().preBindToLocalArray(groupBindTypeHandler, "TRACE:"+pattern, object, params...)
}
// REST registers a http handler to given route pattern according to REST rule.
// REST registers a http handler to give the route pattern according to REST rule.
func (g *RouterGroup) REST(pattern string, object interface{}) *RouterGroup {
return g.Clone().preBindToLocalArray(groupBindTypeRest, pattern, object)
}
@ -261,7 +261,7 @@ func (g *RouterGroup) Middleware(handlers ...HandlerFunc) *RouterGroup {
return g
}
// preBindToLocalArray adds the route registering parameters to internal variable array for lazily registering feature.
// preBindToLocalArray adds the route registering parameters to an internal variable array for lazily registering feature.
func (g *RouterGroup) preBindToLocalArray(bindType string, pattern string, object interface{}, params ...interface{}) *RouterGroup {
_, file, line := gdebug.CallerWithFilter([]string{utils.StackFilterKeyForGoFrame})
preBindItems = append(preBindItems, &preBindItem{
@ -275,7 +275,7 @@ func (g *RouterGroup) preBindToLocalArray(bindType string, pattern string, objec
return g
}
// getPrefix returns the route prefix of the group, which recursively retrieves its parent's prefixo.
// getPrefix returns the route prefix of the group, which recursively retrieves its parent's prefix.
func (g *RouterGroup) getPrefix() string {
prefix := g.prefix
parent := g.parent
@ -317,7 +317,7 @@ func (g *RouterGroup) doBindRoutersToServer(ctx context.Context, item *preBindIt
// Filter repeated char '/'.
pattern = gstr.Replace(pattern, "//", "/")
// Convert params to string array.
// Convert params to a string array.
extras := gconv.Strings(params)
// Check whether it's a hook handler.
@ -384,7 +384,7 @@ func (g *RouterGroup) doBindRoutersToServer(ctx context.Context, item *preBindIt
Middleware: g.middleware,
Source: source,
}
// At last, it treats the `object` as Object registering type.
// Finally, it treats the `object` as the Object registering type.
if g.domain != nil {
g.domain.doBindObject(ctx, in)
} else {

View File

@ -25,6 +25,7 @@ func (s *Server) BindHookHandler(pattern string, hook string, handler HandlerFun
})
}
// doBindHookHandlerInput is the input for BindHookHandler.
type doBindHookHandlerInput struct {
Prefix string
Pattern string
@ -33,6 +34,7 @@ type doBindHookHandlerInput struct {
Source string
}
// doBindHookHandler is the internal handler for BindHookHandler.
func (s *Server) doBindHookHandler(ctx context.Context, in doBindHookHandlerInput) {
s.setHandler(
ctx,
@ -53,6 +55,7 @@ func (s *Server) doBindHookHandler(ctx context.Context, in doBindHookHandlerInpu
)
}
// BindHookHandlerByMap registers handler for specified hook.
func (s *Server) BindHookHandlerByMap(pattern string, hookMap map[string]HandlerFunc) {
for k, v := range hookMap {
s.BindHookHandler(pattern, k, v)

View File

@ -65,7 +65,7 @@ func (s *Server) BindMiddlewareDefault(handlers ...HandlerFunc) {
}
}
// Use is alias of BindMiddlewareDefault.
// Use is the alias of BindMiddlewareDefault.
// See BindMiddlewareDefault.
func (s *Server) Use(handlers ...HandlerFunc) {
s.BindMiddlewareDefault(handlers...)

View File

@ -37,7 +37,7 @@ func (s *Server) serveHandlerKey(method, path, domain string) string {
return strings.ToUpper(method) + ":" + path + strings.ToLower(domain)
}
// getHandlersWithCache searches the router item with cache feature for given request.
// getHandlersWithCache searches the router item with cache feature for a given request.
func (s *Server) getHandlersWithCache(r *Request) (parsedItems []*handlerParsedItem, hasHook, hasServe bool) {
var (
ctx = r.Context()
@ -74,7 +74,7 @@ func (s *Server) getHandlersWithCache(r *Request) (parsedItems []*handlerParsedI
return
}
// searchHandlers retrieves and returns the routers with given parameters.
// searchHandlers retrieve and returns the routers with given parameters.
// Note that the returned routers contain serving handler, middleware handlers and hook handlers.
func (s *Server) searchHandlers(method, path, domain string) (parsedItems []*handlerParsedItem, hasHook, hasServe bool) {
if len(path) == 0 {
@ -109,16 +109,16 @@ func (s *Server) searchHandlers(method, path, domain string) (parsedItems []*han
repeatHandlerCheckMap = make(map[int]struct{}, 16)
)
// Default domain has the most priority when iteration.
// The default domain has the most priority when iteration.
for _, domainItem := range []string{DefaultDomainName, domain} {
p, ok := s.serveTree[domainItem]
if !ok {
continue
}
// Make a list array with capacity of 16.
// Make a list array with a capacity of 16.
lists := make([]*glist.List, 0, 16)
for i, part := range array {
// Add all list of each node to the list array.
// Add all lists of each node to the list array.
if v, ok := p.(map[string]interface{})["*list"]; ok {
lists = append(lists, v.(*glist.List))
}
@ -153,7 +153,7 @@ func (s *Server) searchHandlers(method, path, domain string) (parsedItems []*han
for i := len(lists) - 1; i >= 0; i-- {
for e := lists[i].Front(); e != nil; e = e.Next() {
item := e.Value.(*handlerItem)
// Filter repeated handler item, especially the middleware and hook handlers.
// Filter repeated handler items, especially the middleware and hook handlers.
// It is necessary, do not remove this checks logic unless you really know how it is necessary.
if _, ok := repeatHandlerCheckMap[item.Id]; ok {
continue
@ -183,7 +183,7 @@ func (s *Server) searchHandlers(method, path, domain string) (parsedItems []*han
}
}
switch item.Type {
// The serving handler can be only added just once.
// The serving handler can be added just once.
case HandlerTypeHandler, HandlerTypeObject:
hasServe = true
parsedItemList.PushBack(parsedItem)

View File

@ -17,7 +17,7 @@ import (
"github.com/gogf/gf/v2/text/gstr"
)
// BindHandler registers a handler function to server with given pattern.
// BindHandler registers a handler function to server with a given pattern.
//
// Note that the parameter `handler` can be type of:
// 1. func(*ghttp.Request)
@ -101,7 +101,7 @@ func (s *Server) mergeBuildInNameToPattern(pattern string, structName, methodNam
return uri
}
// nameToUri converts the given name to URL format using following rules:
// nameToUri converts the given name to the URL format using the following rules:
// Rule 0: Convert all method names to lowercase, add char '-' between words.
// Rule 1: Do not convert the method name, construct the URI with the original method name.
// Rule 2: Convert all method names to lowercase, no connecting symbols between words.

View File

@ -17,10 +17,10 @@ import (
"github.com/gogf/gf/v2/text/gstr"
)
// BindObject registers object to server routes with given pattern.
// 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.
// supports multiple method names; multiple methods are separated by char ',', case-sensitive.
func (s *Server) BindObject(pattern string, object interface{}, method ...string) {
var (
bindMethod = ""
@ -38,10 +38,10 @@ func (s *Server) BindObject(pattern string, object interface{}, method ...string
})
}
// BindObjectMethod registers specified method of object to server routes with given pattern.
// 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 supports multiple method names but only one, case-sensitive.
// does not support multiple method names but only one, case-sensitive.
func (s *Server) BindObjectMethod(pattern string, object interface{}, method string) {
s.doBindObjectMethod(context.TODO(), doBindObjectMethodInput{
Prefix: "",
@ -53,7 +53,7 @@ func (s *Server) BindObjectMethod(pattern string, object interface{}, method str
})
}
// BindObjectRest registers object in REST API styles to server with specified pattern.
// BindObjectRest registers object in REST API styles to server with a specified pattern.
func (s *Server) BindObjectRest(pattern string, object interface{}) {
s.doBindObjectRest(context.TODO(), doBindObjectInput{
Prefix: "",

View File

@ -8,6 +8,6 @@ package ghttp
import "github.com/gogf/gf/v2/os/gsession"
// Session is actually a alias of gsession.Session,
// Session is actually an alias of gsession.Session,
// which is bound to a single request.
type Session = gsession.Session

View File

@ -15,23 +15,23 @@ type WebSocket struct {
}
const (
// WsMsgText TextMessage denotes a text data message. The text message payload is
// interpreted as UTF-8 encoded text data.
// 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 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 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 PongMessage denotes a pong control message.
// The optional message payload is UTF-8 encoded text.
WsMsgPong = websocket.PongMessage
)