Selaa lähdekoodia

优化cli模块

lxg 3 vuotta sitten
vanhempi
commit
15225e2407
7 muutettua tiedostoa jossa 62 lisäystä ja 36 poistoa
  1. 12 1
      cmd/main.go
  2. 1 1
      cmd/mock/cli.go
  3. 8 0
      gateway/cli/context.go
  4. 9 14
      gateway/cli/executor.go
  5. 1 1
      gateway/cli/server.go
  6. 30 18
      helper/console/console.go
  7. 1 1
      helper/utils/utils.go

+ 12 - 1
cmd/main.go

@@ -4,6 +4,7 @@ import (
 	"context"
 	"fmt"
 	"git.nspix.com/golang/micro"
+	"git.nspix.com/golang/micro/helper/console"
 	"math/rand"
 	"time"
 )
@@ -27,7 +28,6 @@ func main() {
 		micro.WithPort(6567),
 	)
 
-
 	micro.Handle("getUserList", func(ctx micro.Context) (err error) {
 		var req Request
 		if err = ctx.Bind(&req); err != nil {
@@ -38,6 +38,17 @@ func main() {
 		o.DisableCli = false
 	})
 
+	micro.Handle("/show/contenxt", func(ctx micro.Context) (err error) {
+		table := console.NewTable().WithBordered()
+		table.AddRow("Name", "Age")
+		for i := 0; i < 10; i++ {
+			table.AddRow(fmt.Sprintf("zhansan%d", i), i+12)
+		}
+		return ctx.Success(table)
+	}, func(o *micro.HandleOptions) {
+		o.DisableCli = false
+	})
+
 	go func() {
 		time.AfterFunc(time.Second*5, func() {
 			for i := 0; i < 10; i++ {

+ 1 - 1
cmd/mock/cli.go

@@ -7,7 +7,7 @@ import (
 )
 
 func main() {
-	if conn, err := net.Dial("tcp", "192.168.6.76:6567"); err == nil {
+	if conn, err := net.Dial("tcp", "192.168.4.169:6567"); err == nil {
 		cli.OpenInteractive(context.Background(), conn)
 	}
 }

+ 8 - 0
gateway/cli/context.go

@@ -15,6 +15,10 @@ var (
 	ErrInvalidArgument = errors.New("invalid argument")
 )
 
+type encoder interface {
+	Marshal() ([]byte, error)
+}
+
 type Context struct {
 	ID       int32
 	CmdStr   string
@@ -105,6 +109,10 @@ func (ctx *Context) Error(code int, msg string) (err error) {
 }
 
 func (ctx *Context) Success(i interface{}) (err error) {
+	if v, ok := i.(encoder); ok {
+		ctx.response.Data, err = v.Marshal()
+		return
+	}
 	refVal := reflect.Indirect(reflect.ValueOf(i))
 	switch refVal.Kind() {
 	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:

+ 9 - 14
gateway/cli/executor.go

@@ -4,7 +4,7 @@ import (
 	"errors"
 	"fmt"
 	"git.nspix.com/golang/micro/helper/console"
-	"reflect"
+	"git.nspix.com/golang/micro/helper/unsafestr"
 	"sort"
 	"strings"
 	"sync"
@@ -14,12 +14,6 @@ import (
 
 var (
 	_seq int64
-
-	ErrInvalidHandle         = errors.New("invalid handle kind")
-	ErrInvalidHandleResponse = errors.New("invalid handle response")
-
-	errInterface    = reflect.TypeOf((*error)(nil)).Elem()
-	stringSliceKind = reflect.TypeOf([]string{}).Kind()
 )
 
 type Executor struct {
@@ -121,7 +115,7 @@ func (exec *Executor) Completer(tokens ...string) []string {
 }
 
 func (exec *Executor) String() string {
-	values := make([][]interface{}, 0)
+	table := console.NewTable()
 	var loop func(string, *Executor)
 	loop = func(prefix string, e *Executor) {
 		if e.children == nil {
@@ -137,11 +131,11 @@ func (exec *Executor) String() string {
 		for _, v := range vs {
 			if prefix == "" {
 				if v.handleFunc != nil {
-					values = append(values, []interface{}{v.name, v.getDescription()})
+					table.AddRow(v.name, v.getDescription())
 				}
 			} else {
 				if v.handleFunc != nil {
-					values = append(values, []interface{}{prefix + " " + v.name, v.getDescription()})
+					table.AddRow(prefix+" "+v.name, v.getDescription())
 				}
 			}
 			if prefix == "" {
@@ -152,7 +146,8 @@ func (exec *Executor) String() string {
 		}
 	}
 	loop("", exec)
-	return string(console.Pretty(values, nil))
+	buf, _ := table.Marshal()
+	return unsafestr.BytesToString(buf)
 }
 
 func (exec *Executor) Append(child ...*Executor) *Executor {
@@ -214,12 +209,12 @@ func NewExecutor(args ...string) *Executor {
 	if len(args) > 0 {
 		name = args[0]
 	}
-	if len(args) > 1 {
-		usage = args[1]
-	}
 	if len(args) > 2 {
 		description = args[2]
 	}
+	if len(args) > 1 {
+		usage = args[1]
+	}
 	return &Executor{
 		name:        name,
 		usage:       usage,

+ 1 - 1
gateway/cli/server.go

@@ -106,7 +106,7 @@ func (svr *Server) process(id int32, conn net.Conn) (err error) {
 func (svr *Server) Handle(path string, cb HandleFunc) {
 	var tokens []string
 	if strings.HasPrefix(path, "/") {
-		tokens = strings.Split(path, "/")
+		tokens = strings.Split(path[1:], "/")
 	} else {
 		tokens = utils.BreakUp(path)
 	}

+ 30 - 18
helper/console/console.go

@@ -7,11 +7,18 @@ import (
 	"unicode/utf8"
 )
 
-type Table [][]interface{}
-
-type Options struct {
+type Table struct {
 	Bordered bool
-	Header   bool
+	Values   [][]interface{}
+}
+
+func (table *Table) AddRow(vs ...interface{}) {
+	table.Values = append(table.Values, vs)
+}
+
+func (table *Table) WithBordered() *Table {
+	table.Bordered = true
+	return table
 }
 
 func printBorder(w *bytes.Buffer, ws []int) {
@@ -40,22 +47,20 @@ func calcCharsetWidth(s string) int {
 	}
 }
 
-func Pretty(values Table, opts *Options) []byte {
+func (table *Table) Marshal() ([]byte, error) {
 	columns := make([][]string, 0)
 	var widths []int
 	var width int
 	var maxLength int
-	if opts == nil {
-		opts = &Options{}
-	}
+
 	calcWidth := calcCharsetWidth
-	for _, value := range values {
+	for _, value := range table.Values {
 		if len(value) > maxLength {
 			maxLength = len(value)
 		}
 	}
 	widths = make([]int, maxLength)
-	for _, vs := range values {
+	for _, vs := range table.Values {
 		vl := len(vs)
 		column := make([]string, vl)
 		for i, val := range vs {
@@ -71,20 +76,20 @@ func Pretty(values Table, opts *Options) []byte {
 		columns = append(columns, column)
 	}
 	buffer := &bytes.Buffer{}
-	if opts.Bordered {
+	if table.Bordered {
 		printBorder(buffer, widths)
 	}
 	for index, column := range columns {
 		cl := len(column)
 		for i, w := range widths {
-			if opts.Bordered {
+			if table.Bordered {
 				buffer.WriteString("|")
 			}
 			var str string
 			if cl > i {
 				str = column[i]
 			}
-			if opts.Bordered {
+			if table.Bordered {
 				buffer.WriteString(" ")
 			}
 			buffer.WriteString(str)
@@ -94,21 +99,28 @@ func Pretty(values Table, opts *Options) []byte {
 			}
 			buffer.WriteString(" ")
 			//key value options
-			if len(widths) == 2 && i == 0 && len(column) == 2 && !opts.Bordered && !opts.Header {
+			if len(widths) == 2 && i == 0 && len(column) == 2 && !table.Bordered {
 				buffer.WriteString("\t")
 			}
 		}
-		if opts.Bordered {
+		if table.Bordered {
 			buffer.WriteString("|\n")
 		} else {
 			buffer.WriteString("\n")
 		}
-		if opts.Header && index == 0 {
+		if table.Bordered && index == 0 {
 			printBorder(buffer, widths)
 		}
 	}
-	if opts.Bordered {
+	if table.Bordered {
 		printBorder(buffer, widths)
 	}
-	return buffer.Bytes()
+	return buffer.Bytes(), nil
+}
+
+func NewTable() *Table {
+	return &Table{
+		Bordered: false,
+		Values:   make([][]interface{}, 0),
+	}
 }

+ 1 - 1
helper/utils/utils.go

@@ -52,7 +52,7 @@ func InArray(needle interface{}, haystack interface{}) bool {
 			}
 		}
 	default:
-		panic("haystack: haystack type muset be slice, array or map")
+		panic("haystack: haystack type must be slice, array or map")
 	}
 
 	return false