Skip to content

Commit

Permalink
feat(nnr): update nnr show
Browse files Browse the repository at this point in the history
update nnr show

Signed-off-by: ysicing <i@ysicing.me>
  • Loading branch information
ysicing committed Oct 6, 2023
1 parent 33a622a commit ca4cf7e
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 3 deletions.
22 changes: 20 additions & 2 deletions cmd/nnr/nnr.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import (
"sort"
"strings"

"github.com/ergoapi/util/color"
"github.com/ergoapi/util/output"
"github.com/gosuri/uitable"
"github.com/spf13/cobra"
Expand Down Expand Up @@ -67,12 +68,15 @@ func listServers(f factory.Factory) *cobra.Command {
return cmd
}

var all bool

func listRules(f factory.Factory) *cobra.Command {
cmd := &cobra.Command{
Use: "rules",
Short: "list rules",
RunE: func(cmd *cobra.Command, args []string) error {
api := nnr.New(token)
servers := api.ServersMap()
s, err := api.ListRules()
if err != nil {
return err
Expand All @@ -86,13 +90,27 @@ func listRules(f factory.Factory) *cobra.Command {
return s[i].Traffic >= s[j].Traffic
})
table := uitable.New()
table.AddRow("规则标识", "节点标识", "转发地址", "远程地址", "类型", "流量")
table.AddRow("规则", "节点", "转发地址", "远程地址", "类型", "流量")
for _, index := range s {
table.AddRow(index.Rid, index.Sid, fmt.Sprintf("%v:%v", index.Host, index.Port), fmt.Sprintf("%v:%v", index.Remote, index.RPort), index.Type, util.Traffic(index.Traffic))
rulename := index.Name
sname := index.Sid
value, exist := servers[index.Sid]
if exist {
if all {
sname = fmt.Sprintf("%s(%s)", value.Name, color.SGreen(index.Sid))
} else {
sname = value.Name
}
}
if all {
rulename = fmt.Sprintf("%s(%s)", index.Name, color.SGreen(index.Rid))
}
table.AddRow(rulename, sname, fmt.Sprintf("%v:%v", index.Host, index.Port), fmt.Sprintf("%v:%v", index.Remote, index.RPort), index.Type, util.Traffic(index.Traffic))
}
return output.EncodeTable(os.Stdout, table)
},
}
cmd.Flags().BoolVar(&all, "all", false, "all output")
return cmd
}

Expand Down
12 changes: 12 additions & 0 deletions internal/pkg/nnr/nnr.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,18 @@ func (o *Option) ListServers() ([]Server, error) {
return serversResp.Data, nil
}

func (o *Option) ServersMap() map[string]Server {
s, _ := o.ListServers()
if len(s) == 0 {
return nil
}
m := make(map[string]Server)
for _, j := range s {
m[j.Sid] = j
}
return m
}

func (o *Option) ListRules() ([]Rule, error) {
var rulesResp RulesResp
_, err := o.SetSuccessResult(&rulesResp).Post("https://nnr.moe/api/rules")
Expand Down
2 changes: 1 addition & 1 deletion internal/util/util.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,5 +22,5 @@ func Traffic(k int64) string {
t = t / 1024.0
tunit = "TB"
}
return fmt.Sprintf("%v%v", t, tunit)
return fmt.Sprintf("%.2f%v", t, tunit)
}

0 comments on commit ca4cf7e

Please sign in to comment.