Explorar el Código

优化CLI模式辅助函数

lxg hace 3 años
padre
commit
90e8c8c491
Se han modificado 2 ficheros con 25 adiciones y 1 borrados
  1. 16 0
      gateway/cli/context.go
  2. 9 1
      gateway/cli/server.go

+ 16 - 0
gateway/cli/context.go

@@ -24,12 +24,26 @@ type Context struct {
 	response *Response
 }
 
+//HasArgument 是否有指定的参数
+func (ctx *Context) HasArgument(i int) bool {
+	return len(ctx.Args) > i
+}
+
+//Argument 获取指定参数
+func (ctx *Context) Argument(i int) string {
+	if ctx.HasArgument(i) {
+		return ctx.Args[i]
+	}
+	return ""
+}
+
 func (ctx *Context) reset(s string) {
 	ctx.response = &Response{}
 	ctx.Args = nil
 	ctx.CmdStr = s
 }
 
+//Get 获取一个session变量
 func (ctx *Context) Get(s string) interface{} {
 	ctx.locker.RLock()
 	defer ctx.locker.RUnlock()
@@ -39,6 +53,7 @@ func (ctx *Context) Get(s string) interface{} {
 	return ctx.Values[s]
 }
 
+//Set 设置一个session变量
 func (ctx *Context) Set(key string, value interface{}) {
 	ctx.locker.Lock()
 	defer ctx.locker.Unlock()
@@ -48,6 +63,7 @@ func (ctx *Context) Set(key string, value interface{}) {
 	ctx.Values[key] = value
 }
 
+//Bind 绑定一个变量
 func (ctx *Context) Bind(i interface{}) (err error) {
 	refVal := reflect.Indirect(reflect.ValueOf(i))
 	refType := refVal.Type()

+ 9 - 1
gateway/cli/server.go

@@ -104,7 +104,12 @@ func (svr *Server) process(id int32, conn net.Conn) (err error) {
 }
 
 func (svr *Server) Handle(path string, cb HandleFunc) {
-	tokens := utils.BreakUp(path)
+	var tokens []string
+	if strings.HasPrefix(path, "/") {
+		tokens = strings.Split(path, "/")
+	} else {
+		tokens = utils.BreakUp(path)
+	}
 	svr.locker.Lock()
 	defer svr.locker.Unlock()
 	var (
@@ -117,6 +122,9 @@ func (svr *Server) Handle(path string, cb HandleFunc) {
 	p = svr.executor
 	for i, token := range tokens {
 		token = strings.TrimSpace(strings.ToLower(token))
+		if token == ""{
+			continue
+		}
 		if q, err = p.Children(token); err == nil {
 			if i == length-1 {
 				panic(path + " already exists")