fix(mtr): 提前冲突校验并修复 report 模式 CJK 对齐

- 将 MTR 冲突检查前移到所有 early-return 分支之前,避免 `-r --from`、`-t --fast-trace`、`--file` 等组合绕过校验
- report 输出改用 `go-runewidth` 计算显示宽度与截断(`StringWidth`/`Truncate`)
- 新增 `reportPadRight`,替换 `%*s` 对齐路径,修复中文场景下 HOST 与指标列错位
- 保持 wide/非 wide 逻辑不变,仅修复布局与参数校验时序
- tests: `go test -ldflags "-checklinkname=0" ./...`
This commit is contained in:
tsosunchia committed 2026-02-27 21:51:38 +08:00
1 parent 24224cf943
commit ae08ec9796
7 files changed
+407 -86

No files matched your search

+37 -18
View File
@@ -298,22 +298,31 @@ export NO_COLOR=1
```bash
# MTR mode: continuous probing with ICMP (default), refreshes table in real-time
nexttrace -t 1.1.1.1
# or equivalently:
nexttrace --mtr 1.1.1.1
# MTR mode with TCP SYN probing
nexttrace --mtr --tcp --port 443 www.bing.com
nexttrace -t --tcp --port 443 www.bing.com
# MTR mode with UDP probing
nexttrace --mtr --udp 1.0.0.1
nexttrace -t --udp 1.0.0.1
# Set the interval between rounds (default: 1000ms)
nexttrace --mtr --mtr-interval 500 1.1.1.1
# Set the interval between rounds (default: 1000ms in MTR)
nexttrace -t -i 500 1.1.1.1
# Limit the number of rounds (default: 0 = infinite, press Ctrl-C to stop)
nexttrace --mtr --mtr-max-rounds 10 1.1.1.1
# Limit the number of rounds (default: infinite in TUI, 10 in report mode)
nexttrace -t -q 20 1.1.1.1
# Report mode: run N rounds and print a final summary (like mtr -r)
nexttrace -r 1.1.1.1 # = --mtr --report, 10 rounds by default
nexttrace -r -q 5 1.1.1.1 # 5 rounds
# Wide report: no host column truncation (like mtr -rw)
nexttrace -w 1.1.1.1 # = --mtr --report --wide
# Combine with other options
nexttrace --mtr --tcp --max-hops 20 --first 3 --no-rdns 8.8.8.8
nexttrace -t --tcp --max-hops 20 --first 3 --no-rdns 8.8.8.8
```
When running in a terminal (TTY), MTR mode uses an **interactive full-screen TUI**:
@@ -329,6 +338,15 @@ When running in a terminal (TTY), MTR mode uses an **interactive full-screen TUI
- Uses the **alternate screen buffer**, so your previous terminal history is preserved on exit.
- When stdin is not a TTY (e.g. piped), it falls back to a simple table refresh.
The **report mode** (`-r`/`--report`) produces a one-shot summary after all rounds complete, suitable for scripting:
```
Start: 2025-07-14T09:12:00+0800
HOST: myhost Loss% Snt Last Avg Best Wrst StDev
1.|-- AS4134 10.0.0.1 0.0% 10 1.23 1.45 0.98 2.10 0.32
2.|-- ??? 100.0% 10 0.00 0.00 0.00 0.00 0.00
```
> Note: `--mtr` cannot be used together with `--table`, `--raw`, `--classic`, `--json`, `--output`, `--route-path`, `--from`, `--fast-trace`, `--file`, or `--deploy`.
#### `NextTrace` supports users to select their own IP API (currently supports: `LeoMoeAPI`, `IP.SB`, `IPInfo`, `IPInsight`, `IPAPI.com`, `IPInfoLocal`, `CHUNZHEN`)
@@ -364,7 +382,7 @@ nexttrace -tcp --queries 2 --parallel-requests 1 --table --route-path 2001:4860:
Equivalent to:
nexttrace -d ip-api.com -m 20 -T -p 443 -q 5 -n 1.1.1.1
nexttrace -T -q 2 --parallel-requests 1 -t -P 2001:4860:4860::8888
nexttrace -T -q 2 --parallel-requests 1 --table -P 2001:4860:4860::8888
```
### Globalping
@@ -409,8 +427,8 @@ usage: nexttrace [-h|--help] [--init] [-4|--ipv4] [-6|--ipv6] [-T|--tcp]
[-m|--max-hops <integer>] [-d|--data-provider
(IP.SB|ip.sb|IPInfo|ipinfo|IPInsight|ipinsight|IPAPI.com|ip-api.com|IPInfoLocal|ipinfolocal|chunzhen|LeoMoeAPI|leomoeapi|ipdb.one|disable-geoip)]
[--pow-provider (api.nxtrace.org|sakura)] [-n|--no-rdns]
[-a|--always-rdns] [-P|--route-path] [-r|--report] [--dn42]
[-o|--output] [-t|--table] [--raw] [-j|--json] [-c|--classic]
[-a|--always-rdns] [-P|--route-path] [--dn42]
[-o|--output] [--table] [--raw] [-j|--json] [-c|--classic]
[-f|--first <integer>] [-M|--map] [-e|--disable-mpls]
[-V|--version] [-s|--source "<value>"] [--source-port
<integer>] [-D|--dev "<value>"] [--listen "<value>"]
@@ -419,7 +437,7 @@ usage: nexttrace [-h|--help] [--init] [-4|--ipv4] [-6|--ipv6] [-T|--tcp]
[_positionalArg_nexttrace_38 "<value>"] [--dot-server
(dnssb|aliyun|dnspod|google|cloudflare)] [-g|--language
(en|cn)] [--file "<value>"] [-C|--no-color] [--from "<value>"]
[--mtr] [--mtr-interval <integer>] [--mtr-max-rounds <integer>]
[-t|--mtr] [-r|--report] [-w|--wide]
An open source visual route tracking CLI tool
@@ -462,11 +480,10 @@ Arguments:
domain names
-P --route-path Print traceroute hop path by ASN and
location
-r --report output using report mode
--dn42 DN42 Mode
-o --output Write trace result to file
(RealTimePrinter ONLY)
-t --table Output trace results as table
--table Output trace results as table
--raw An Output Easy to Parse
-j --json Output trace results as JSON
-c --classic Classic Output trace results like
@@ -493,6 +510,8 @@ Arguments:
sending packets groups by TTL. Useful when
some routers use rate-limit for ICMP
messages. Default: 50
(In MTR mode, also controls interval
between rounds. Default: 1000)
--timeout The number of [milliseconds] to keep probe
sockets open before giving up on the
connection. Default: 1000
@@ -509,12 +528,12 @@ Arguments:
specified location. The location field
accepts continents, countries, regions,
cities, ASNs, ISPs, or cloud regions.
--mtr Enable MTR (My Traceroute) continuous
-t --mtr Enable MTR (My Traceroute) continuous
probing mode
--mtr-interval Set interval between MTR rounds in
milliseconds. Default: 1000
--mtr-max-rounds Set maximum MTR rounds (0 = infinite
until Ctrl-C). Default: 0
-r --report MTR report mode: run N rounds then print
summary. Implies --mtr. Default rounds: 10
-w --wide Wide report mode: no host column
truncation. Implies --mtr --report
```
## Project screenshot
+37 -18
View File
@@ -296,22 +296,31 @@ export NO_COLOR=1
```bash
# MTR 模式:使用 ICMP(默认)连续探测,实时刷新表格
nexttrace -t 1.1.1.1
# 等价写法:
nexttrace --mtr 1.1.1.1
# MTR 模式使用 TCP SYN 探测
nexttrace --mtr --tcp --port 443 www.bing.com
nexttrace -t --tcp --port 443 www.bing.com
# MTR 模式使用 UDP 探测
nexttrace --mtr --udp 1.0.0.1
nexttrace -t --udp 1.0.0.1
# 设置每轮间隔(默认 1000ms)
nexttrace --mtr --mtr-interval 500 1.1.1.1
# 设置每轮间隔(MTR 模式下默认 1000ms)
nexttrace -t -i 500 1.1.1.1
# 限制最大轮次(默认 0 = 无限,按 Ctrl-C 停止)
nexttrace --mtr --mtr-max-rounds 10 1.1.1.1
# 限制最大轮次(TUI 默认无限,报告模式默认 10)
nexttrace -t -q 20 1.1.1.1
# 报告模式:运行 N 轮后一次性输出统计摘要(类似 mtr -r)
nexttrace -r 1.1.1.1 # = --mtr --report,默认 10 轮
nexttrace -r -q 5 1.1.1.1 # 5 轮
# 宽报告模式:主机列不截断(类似 mtr -rw)
nexttrace -w 1.1.1.1 # = --mtr --report --wide
# 与其他选项组合使用
nexttrace --mtr --tcp --max-hops 20 --first 3 --no-rdns 8.8.8.8
nexttrace -t --tcp --max-hops 20 --first 3 --no-rdns 8.8.8.8
```
在终端(TTY)中运行时,MTR 模式使用**交互式全屏 TUI**:
@@ -327,6 +336,15 @@ nexttrace --mtr --tcp --max-hops 20 --first 3 --no-rdns 8.8.8.8
- 使用**备用屏幕缓冲区**,退出后恢复之前的终端历史记录。
- 当 stdin 非 TTY(如管道输入)时,降级为简单表格刷新模式。
**报告模式**(`-r`/`--report`)在所有轮次完成后一次性输出统计,适合脚本使用:
```
Start: 2025-07-14T09:12:00+0800
HOST: myhost Loss% Snt Last Avg Best Wrst StDev
1.|-- AS4134 10.0.0.1 0.0% 10 1.23 1.45 0.98 2.10 0.32
2.|-- ??? 100.0% 10 0.00 0.00 0.00 0.00 0.00
```
> 注意:`--mtr` 不可与 `--table`、`--raw`、`--classic`、`--json`、`--output`、`--route-path`、`--from`、`--fast-trace`、`--file`、`--deploy` 同时使用。
#### `NextTrace`支持用户自主选择 IP 数据库(目前支持:`LeoMoeAPI`, `IP.SB`, `IPInfo`, `IPInsight`, `IPAPI.com`, `IPInfoLocal`, `CHUNZHEN`)
@@ -361,7 +379,7 @@ nexttrace -tcp --queries 2 --parallel-requests 1 --table --route-path 2001:4860:
Equivalent to:
nexttrace -d ip-api.com -m 20 -T -p 443 -q 5 -n 1.1.1.1
nexttrace -T -q 2 --parallel-requests 1 -t -P 2001:4860:4860::8888
nexttrace -T -q 2 --parallel-requests 1 --table -P 2001:4860:4860::8888
```
### Globalping
@@ -391,8 +409,8 @@ usage: nexttrace [-h|--help] [--init] [-4|--ipv4] [-6|--ipv6] [-T|--tcp]
[-m|--max-hops <integer>] [-d|--data-provider
(IP.SB|ip.sb|IPInfo|ipinfo|IPInsight|ipinsight|IPAPI.com|ip-api.com|IPInfoLocal|ipinfolocal|chunzhen|LeoMoeAPI|leomoeapi|ipdb.one|disable-geoip)]
[--pow-provider (api.nxtrace.org|sakura)] [-n|--no-rdns]
[-a|--always-rdns] [-P|--route-path] [-r|--report] [--dn42]
[-o|--output] [-t|--table] [--raw] [-j|--json] [-c|--classic]
[-a|--always-rdns] [-P|--route-path] [--dn42]
[-o|--output] [--table] [--raw] [-j|--json] [-c|--classic]
[-f|--first <integer>] [-M|--map] [-e|--disable-mpls]
[-V|--version] [-s|--source "<value>"] [--source-port
<integer>] [-D|--dev "<value>"] [--listen "<value>"]
@@ -401,7 +419,7 @@ usage: nexttrace [-h|--help] [--init] [-4|--ipv4] [-6|--ipv6] [-T|--tcp]
[_positionalArg_nexttrace_38 "<value>"] [--dot-server
(dnssb|aliyun|dnspod|google|cloudflare)] [-g|--language
(en|cn)] [--file "<value>"] [-C|--no-color] [--from "<value>"]
[--mtr] [--mtr-interval <integer>] [--mtr-max-rounds <integer>]
[-t|--mtr] [-r|--report] [-w|--wide]
An open source visual route tracking CLI tool
@@ -444,11 +462,10 @@ Arguments:
domain names
-P --route-path Print traceroute hop path by ASN and
location
-r --report output using report mode
--dn42 DN42 Mode
-o --output Write trace result to file
(RealTimePrinter ONLY)
-t --table Output trace results as table
--table Output trace results as table
--raw An Output Easy to Parse
-j --json Output trace results as JSON
-c --classic Classic Output trace results like
@@ -475,6 +492,8 @@ Arguments:
sending packets groups by TTL. Useful when
some routers use rate-limit for ICMP
messages. Default: 50
(In MTR mode, also controls interval
between rounds. Default: 1000)
--timeout The number of [milliseconds] to keep probe
sockets open before giving up on the
connection. Default: 1000
@@ -491,12 +510,12 @@ Arguments:
specified location. The location field
accepts continents, countries, regions,
cities, ASNs, ISPs, or cloud regions.
--mtr Enable MTR (My Traceroute) continuous
-t --mtr Enable MTR (My Traceroute) continuous
probing mode
--mtr-interval Set interval between MTR rounds in
milliseconds. Default: 1000
--mtr-max-rounds Set maximum MTR rounds (0 = infinite
until Ctrl-C). Default: 0
-r --report MTR report mode: run N rounds then print
summary. Implies --mtr. Default rounds: 10
-w --wide Wide report mode: no host column
truncation. Implies --mtr --report
```
## 项目截图
+72 -25
View File
@@ -185,7 +185,7 @@ func Execute() {
routePath := parser.Flag("P", "route-path", &argparse.Options{Help: "Print traceroute hop path by ASN and location"})
dn42 := parser.Flag("", "dn42", &argparse.Options{Help: "DN42 Mode"})
output := parser.Flag("o", "output", &argparse.Options{Help: "Write trace result to file (RealTimePrinter ONLY)"})
tablePrint := parser.Flag("t", "table", &argparse.Options{Help: "Output trace results as a final summary table (report mode)"})
tablePrint := parser.Flag("", "table", &argparse.Options{Help: "Output trace results as a final summary table (traceroute report mode)"})
rawPrint := parser.Flag("", "raw", &argparse.Options{Help: "An Output Easy to Parse"})
jsonPrint := parser.Flag("j", "json", &argparse.Options{Help: "Output trace results as JSON"})
classicPrint := parser.Flag("c", "classic", &argparse.Options{Help: "Classic Output trace results like BestTrace"})
@@ -211,9 +211,9 @@ func Execute() {
file := parser.String("", "file", &argparse.Options{Help: "Read IP Address or domain name from file"})
noColor := parser.Flag("C", "no-color", &argparse.Options{Help: "Disable Colorful Output"})
from := parser.String("", "from", &argparse.Options{Help: "Run traceroute via Globalping (https://globalping.io/network) from a specified location. The location field accepts continents, countries, regions, cities, ASNs, ISPs, or cloud regions."})
mtrMode := parser.Flag("", "mtr", &argparse.Options{Help: "Enable MTR (My Traceroute) continuous probing mode"})
mtrInterval := parser.Int("", "mtr-interval", &argparse.Options{Default: 1000, Help: "Set interval between MTR rounds in milliseconds (default: 1000)"})
mtrMaxRounds := parser.Int("", "mtr-max-rounds", &argparse.Options{Default: 0, Help: "Set maximum MTR rounds (0 = infinite until Ctrl-C)"})
mtrMode := parser.Flag("t", "mtr", &argparse.Options{Help: "Enable MTR (My Traceroute) continuous probing mode"})
reportMode := parser.Flag("r", "report", &argparse.Options{Help: "MTR report mode (non-interactive, implies --mtr); can trigger MTR without --mtr"})
wideMode := parser.Flag("w", "wide", &argparse.Options{Help: "MTR wide report mode (implies --mtr --report); alone equals --mtr --report --wide"})
err := parser.Parse(os.Args)
if err != nil {
@@ -223,13 +223,53 @@ func Execute() {
return
}
// ── 统一 MTR 有效开关 ──
effectiveMTR := *mtrMode || *reportMode || *wideMode
effectiveReport := *reportMode || *wideMode
effectiveWide := *wideMode
// MTR 冲突检查必须在所有可能 early-return 的分支之前执行
if effectiveMTR {
conflictFlags := map[string]bool{
"table": *tablePrint,
"raw": *rawPrint,
"classic": *classicPrint,
"json": *jsonPrint,
"output": *output,
"routePath": *routePath,
"from": *from != "",
"fastTrace": *fast_trace,
"file": *file != "",
"deploy": *deploy,
}
if conflict, ok := checkMTRConflicts(conflictFlags); !ok {
fmt.Printf("--mtr 不能与 %s 同时使用\n", conflict)
os.Exit(1)
}
}
// 判定 -q / -i 是否显式传入(用于 MTR 下参数迁移)
queriesExplicit := false
ttlTimeExplicit := false
for _, a := range parser.GetArgs() {
if !a.GetParsed() {
continue
}
switch a.GetLname() {
case "queries":
queriesExplicit = true
case "ttl-time":
ttlTimeExplicit = true
}
}
if *noColor {
color.NoColor = true
} else {
color.NoColor = false
}
if !*jsonPrint {
if !*jsonPrint && !effectiveMTR {
printer.Version()
}
@@ -400,7 +440,7 @@ func Execute() {
//}()
// MTR 使用 TUI 备用屏,必须在 wshandle.New() / GetFastIP 之前
// 禁止彩色横幅输出,避免污染主终端历史。
if *mtrMode {
if effectiveMTR {
util.SuppressFastIPOutput = true
}
@@ -515,7 +555,7 @@ func Execute() {
*packetSize = 2
}
if !*jsonPrint && !*mtrMode {
if !*jsonPrint && !effectiveMTR {
printer.PrintTraceRouteNav(ip, domain, *dataOrigin, *maxHops, *packetSize, *srcAddr, string(m))
}
@@ -550,27 +590,34 @@ func Execute() {
}
// ── MTR 连续探测模式 ──
if *mtrMode {
conflictFlags := map[string]bool{
"table": *tablePrint,
"raw": *rawPrint,
"classic": *classicPrint,
"json": *jsonPrint,
"output": *output,
"routePath": *routePath,
"from": *from != "",
"fastTrace": *fast_trace,
"file": *file != "",
"deploy": *deploy,
if effectiveMTR {
// MTR 下 -q/-i 参数迁移
var mtrMaxRounds int
var mtrIntervalMs int
if effectiveReport {
if queriesExplicit {
mtrMaxRounds = *numMeasurements
} else {
mtrMaxRounds = 10 // report 默认 10 轮
}
} else {
if queriesExplicit {
mtrMaxRounds = *numMeasurements
} else {
mtrMaxRounds = 0 // 非 report → 无限
}
}
if conflict, ok := checkMTRConflicts(conflictFlags); !ok {
fmt.Printf("--mtr 不能与 %s 同时使用\n", conflict)
os.Exit(1)
if ttlTimeExplicit {
mtrIntervalMs = *ttlInterval
} else {
mtrIntervalMs = 1000 // MTR 默认 1000ms
}
if *numMeasurements != 1 {
fmt.Println("[MTR] --queries 在 MTR 模式下无效,已重置为 1")
if effectiveReport {
runMTRReport(m, conf, mtrIntervalMs, mtrMaxRounds, domain, *dataOrigin, effectiveWide)
} else {
runMTRTUI(m, conf, mtrIntervalMs, mtrMaxRounds, domain, *dataOrigin)
}
runMTRMode(m, conf, *mtrInterval, *mtrMaxRounds, domain, *dataOrigin)
return
}
+72 -6
View File
@@ -42,10 +42,10 @@ func checkMTRConflicts(flags map[string]bool) (conflict string, ok bool) {
return "", true
}
// runMTRMode 执行 MTR 连续探测模式。
// 当 stdin 为 TTY 时启用交互式 TUI(备用屏幕、按键控制);
// runMTRTUI 执行 MTR 交互式 TUI 模式。
// 当 stdin 为 TTY 时启用全屏 TUI(备用屏幕、按键控制);
// 非 TTY 时降级为简单表格刷新。
func runMTRMode(method trace.Method, conf trace.Config, intervalMs int, maxRounds int, domain string, dataOrigin string) {
func runMTRTUI(method trace.Method, conf trace.Config, intervalMs int, maxRounds int, domain string, dataOrigin string) {
if intervalMs <= 0 {
intervalMs = 1000
}
@@ -111,6 +111,68 @@ func runMTRMode(method trace.Method, conf trace.Config, intervalMs int, maxRound
}
}
// runMTRReport 执行 MTR 非全屏报告模式(对齐 mtr -rzw 风格)。
// 探测完 maxRounds 后一次性输出最终统计到 stdout,不进入 alternate screen。
func runMTRReport(method trace.Method, conf trace.Config, intervalMs int, maxRounds int, domain string, dataOrigin string, wide bool) {
if intervalMs <= 0 {
intervalMs = 1000
}
if maxRounds <= 0 {
maxRounds = 10
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
sigCh := make(chan os.Signal, 1)
signal.Notify(sigCh, os.Interrupt, syscall.SIGTERM)
go func() {
<-sigCh
cancel()
}()
startTime := time.Now()
srcHost, _ := os.Hostname()
if srcHost == "" {
srcHost = "unknown-host"
}
lang := conf.Lang
if lang == "" {
lang = "cn"
}
// 最终快照
var finalStats []trace.MTRHopStat
onSnapshot := func(iteration int, stats []trace.MTRHopStat) {
finalStats = stats
}
opts := trace.MTROptions{
Interval: time.Duration(intervalMs) * time.Millisecond,
MaxRounds: maxRounds,
}
err := trace.RunMTR(ctx, method, conf, opts, onSnapshot)
if err != nil && err != context.Canceled {
fmt.Println(err)
return
}
if len(finalStats) == 0 {
fmt.Println("No data collected.")
return
}
printer.MTRReportPrint(finalStats, printer.MTRReportOptions{
StartTime: startTime,
SrcHost: srcHost,
Wide: wide,
Lang: lang,
})
}
// resolveSrcIP 按优先级解析源 IP:--source > --dev 推导 > udp dial fallback。
// 保证与目标 IP 族匹配,失败时返回 "unknown"。
func resolveSrcIP(conf trace.Config) string {
@@ -153,9 +215,13 @@ func buildAPIInfo(dataOrigin string) string {
if !strings.EqualFold(dataOrigin, "LeoMoeAPI") && !strings.EqualFold(dataOrigin, "leomoeapi") {
return ""
}
ip := util.FastIpCache
if ip == "" {
meta := util.FastIPMetaCache
if meta.IP == "" {
return ""
}
return fmt.Sprintf("preferred API IP: %s", ip)
nodeName := meta.NodeName
if nodeName == "" {
nodeName = "Unknown"
}
return fmt.Sprintf("preferred API IP: %s[%s]", nodeName, meta.IP)
}
+162 -9
View File
@@ -2,10 +2,14 @@ package printer
import (
"fmt"
"os"
"strings"
"time"
"github.com/fatih/color"
"github.com/mattn/go-runewidth"
"github.com/rodaine/table"
"golang.org/x/term"
"github.com/nxtrace/NTrace-core/ipgeo"
"github.com/nxtrace/NTrace-core/trace"
@@ -175,24 +179,29 @@ func geoField(cn, en, lang string) string {
// HostModeCity (1): + 城市/省份/国家
// HostModeOwner (2): + 运营商
// HostModeFull (3): + 完整地址 + 运营商
//
// ASN 始终作为前缀(对齐 mtr -rw 风格):
//
// "AS13335 one.one.one.one" (模式 0)
// "AS13335 one.one.one.one US" (模式 1)
func formatMTRHostByMode(s trace.MTRHopStat, mode int, nameMode int, lang string) string {
base := formatMTRHostBase(s, nameMode)
if s.Geo == nil {
return base
}
var segs []string
// ASN 在所有模式下都展示
// ASN 作为前缀
asnPrefix := ""
if s.Geo.Asnumber != "" {
segs = append(segs, "AS"+s.Geo.Asnumber)
asnPrefix = "AS" + s.Geo.Asnumber
}
var segs []string
switch mode {
case HostModeASN:
// 仅 ASN,无额外 geo
case HostModeCity:
// 单级回退链:city -> prov -> country,取最具体的一个
city := geoField(s.Geo.City, s.Geo.CityEn, lang)
prov := geoField(s.Geo.Prov, s.Geo.ProvEn, lang)
country := geoField(s.Geo.Country, s.Geo.CountryEn, lang)
@@ -233,11 +242,17 @@ func formatMTRHostByMode(s trace.MTRHopStat, mode int, nameMode int, lang string
}
}
geo := strings.Join(segs, ", ")
if geo == "" {
return base
// 拼接顺序:asnPrefix + base + geo
var parts []string
if asnPrefix != "" {
parts = append(parts, asnPrefix)
}
return base + " " + geo
parts = append(parts, base)
geo := strings.Join(segs, ", ")
if geo != "" {
parts = append(parts, geo)
}
return strings.Join(parts, " ")
}
// formatMTRHostWithMPLS 构建 Host 列完整内容(含内联 MPLS),供表格打印器使用。
@@ -307,3 +322,141 @@ func formatMTRGeoData(data *ipgeo.IPGeoData) string {
return strings.Join(segs, ", ")
}
// ---------------------------------------------------------------------------
// MTR Report 模式打印器(对齐 mtr -rzw 风格)
// ---------------------------------------------------------------------------
// MTRReportOptions 控制报告输出细节。
type MTRReportOptions struct {
StartTime time.Time
SrcHost string
Wide bool
Lang string
}
// MTRReportPrint 以 mtr -rzw 风格将最终统计一次性输出到 stdout。
//
// 输出格式(示例):
//
// Start: 2025-07-14T09:12:00+0800
// HOST: myhost Loss% Snt Last Avg Best Wrst StDev
// 1. AS4134 one.one.one.one 0.0% 10 1.23 1.45 0.98 2.10 0.32
// 2. ??? 100.0% 10 0.00 0.00 0.00 0.00 0.00
//
// Wide 模式下使用 HostModeFull(完整地址 + 运营商),host 列宽度取所有行最大值;
// 非 wide 模式使用 HostModeASN,按终端宽度截断:
//
// width < 100 → maxHost = 16
// 100 ≤ width < 140 → maxHost = 20
// width ≥ 140 → maxHost = 24
func MTRReportPrint(stats []trace.MTRHopStat, opts MTRReportOptions) {
lang := opts.Lang
if lang == "" {
lang = "cn"
}
// wide 模式使用完整地址,非 wide 仅 ASN
hostMode := HostModeASN
if opts.Wide {
hostMode = HostModeFull
}
// Start 行
fmt.Printf("Start: %s\n", opts.StartTime.Format("2006-01-02T15:04:05-0700"))
// 预先格式化所有 host 字符串,以便确定对齐宽度
hosts := make([]string, len(stats))
for i, s := range stats {
hosts[i] = formatMTRHostWithMPLS(s, hostMode, HostNamePTRorIP, lang)
}
// 确定 host 列对齐宽度
var hostColW int
if opts.Wide {
// wide: 取所有 host + 表头中的最大可视宽度
hostColW = reportDisplayWidth(opts.SrcHost)
for _, h := range hosts {
if w := reportDisplayWidth(h); w > hostColW {
hostColW = w
}
}
hostColW++ // 加 1 列间距
} else {
tw, _, err := term.GetSize(int(os.Stdout.Fd()))
if err != nil || tw <= 0 {
tw = 80
}
switch {
case tw < 100:
hostColW = 16
case tw < 140:
hostColW = 20
default:
hostColW = 24
}
// 截断 host 到 hostColW
for i, h := range hosts {
if reportDisplayWidth(h) > hostColW {
hosts[i] = reportTruncateToWidth(h, hostColW)
}
}
}
// 度量列格式:右对齐,固定宽度
const metricsFmt = " %6s %5s %6s %6s %6s %6s %6s"
// HOST 表头行
hostHeader := opts.SrcHost
if !opts.Wide && reportDisplayWidth(hostHeader) > hostColW {
hostHeader = reportTruncateToWidth(hostHeader, hostColW)
}
headerMetrics := fmt.Sprintf(metricsFmt, "Loss%", "Snt", "Last", "Avg", "Best", "Wrst", "StDev")
fmt.Printf("HOST: %s%s\n", reportPadRight(hostHeader, hostColW), headerMetrics)
// 数据行
// 前缀 " N. " 占 5 字符(%3d. + 空格),与 "HOST: " 的 6 字符差 1,
// 将额外 1 格留给 host 列左侧自然padding。
prevTTL := 0
for i, s := range stats {
prefix := fmt.Sprintf("%3d. ", s.TTL)
if s.TTL == prevTTL {
prefix = " "
}
prevTTL = s.TTL
metrics := fmt.Sprintf(metricsFmt,
formatLoss(s.Loss),
fmt.Sprint(s.Snt),
formatMs(s.Last),
formatMs(s.Avg),
formatMs(s.Best),
formatMs(s.Wrst),
formatMs(s.StDev),
)
fmt.Printf("%s%s%s\n", prefix, reportPadRight(hosts[i], hostColW), metrics)
}
}
// reportDisplayWidth 返回字符串的终端显示宽度(CJK 字符占 2 列)。
func reportDisplayWidth(s string) int {
return runewidth.StringWidth(s)
}
// reportTruncateToWidth 将字符串按终端显示宽度截断(CJK 安全)。
func reportTruncateToWidth(s string, maxW int) string {
if runewidth.StringWidth(s) <= maxW {
return s
}
return runewidth.Truncate(s, maxW, "")
}
// reportPadRight 将 s 用空格右填充到 width 显示列宽(CJK 安全)。
func reportPadRight(s string, width int) string {
w := runewidth.StringWidth(s)
if w >= width {
return s
}
return s + strings.Repeat(" ", width-w)
}
+10 -10
View File
@@ -105,7 +105,7 @@ func TestMTRRenderTable_EmptyHostname(t *testing.T) {
t.Fatalf("expected 1 row, got %d", len(rows))
}
// 无 hostname 时只显示 IP + Geo
want := "8.8.8.8 AS15169, United States"
want := "AS15169 8.8.8.8 United States"
if rows[0].Host != want {
t.Errorf("Host = %q, want %q", rows[0].Host, want)
}
@@ -120,7 +120,7 @@ func TestMTRRenderTable_HostnameAndIP(t *testing.T) {
}},
}
rows := MTRRenderTable(stats, HostModeFull, HostNamePTRorIP, "en")
want := "one.one.one.one AS13335, US, Cloudflare"
want := "AS13335 one.one.one.one US, Cloudflare"
if rows[0].Host != want {
t.Errorf("Host = %q, want %q", rows[0].Host, want)
}
@@ -796,7 +796,7 @@ func TestFormatMTRHostByMode_ASN(t *testing.T) {
},
}
got := formatMTRHostByMode(s, HostModeASN, HostNamePTRorIP, "en")
want := "one.one.one.one AS13335"
want := "AS13335 one.one.one.one"
if got != want {
t.Errorf("HostModeASN: got %q, want %q", got, want)
}
@@ -814,7 +814,7 @@ func TestFormatMTRHostByMode_City(t *testing.T) {
},
}
got := formatMTRHostByMode(s, HostModeCity, HostNamePTRorIP, "en")
want := "1.1.1.1 AS13335, Los Angeles"
want := "AS13335 1.1.1.1 Los Angeles"
if got != want {
t.Errorf("HostModeCity: got %q, want %q", got, want)
}
@@ -830,7 +830,7 @@ func TestFormatMTRHostByMode_Owner(t *testing.T) {
},
}
got := formatMTRHostByMode(s, HostModeOwner, HostNamePTRorIP, "en")
want := "1.1.1.1 AS13335, Cloudflare"
want := "AS13335 1.1.1.1 Cloudflare"
if got != want {
t.Errorf("HostModeOwner: got %q, want %q", got, want)
}
@@ -848,7 +848,7 @@ func TestFormatMTRHostByMode_Full(t *testing.T) {
},
}
got := formatMTRHostByMode(s, HostModeFull, HostNamePTRorIP, "en")
want := "one.one.one.one AS13335, US, Cloudflare"
want := "AS13335 one.one.one.one US, Cloudflare"
if got != want {
t.Errorf("HostModeFull: got %q, want %q", got, want)
}
@@ -923,13 +923,13 @@ func TestFormatMTRHostByMode_LangCN(t *testing.T) {
},
}
got := formatMTRHostByMode(s, HostModeCity, HostNamePTRorIP, "cn")
want := "1.1.1.1 AS13335, 洛杉矶"
want := "AS13335 1.1.1.1 洛杉矶"
if got != want {
t.Errorf("HostModeCity cn: got %q, want %q", got, want)
}
got = formatMTRHostByMode(s, HostModeCity, HostNamePTRorIP, "en")
want = "1.1.1.1 AS13335, Los Angeles"
want = "AS13335 1.1.1.1 Los Angeles"
if got != want {
t.Errorf("HostModeCity en: got %q, want %q", got, want)
}
@@ -1111,7 +1111,7 @@ func TestFormatMTRHostByMode_IPOnly_ShowsIP(t *testing.T) {
}
// HostNameIPOnly 时 base 始终是 IP,即使有 PTR
got := formatMTRHostByMode(s, HostModeFull, HostNameIPOnly, "en")
want := "1.1.1.1 AS13335, US, Cloudflare"
want := "AS13335 1.1.1.1 US, Cloudflare"
if got != want {
t.Errorf("HostModeFull+IPOnly: got %q, want %q", got, want)
}
@@ -1129,7 +1129,7 @@ func TestFormatMTRHostByMode_PTRorIP_ShowsPTR(t *testing.T) {
},
}
got := formatMTRHostByMode(s, HostModeFull, HostNamePTRorIP, "en")
want := "one.one.one.one AS13335, US, Cloudflare"
want := "AS13335 one.one.one.one US, Cloudflare"
if got != want {
t.Errorf("HostModeFull+PTRorIP: got %q, want %q", got, want)
}
+17
View File
@@ -27,6 +27,16 @@ var (
)
var FastIpCache = ""
// FastIPMeta 存储 FastIP 节点的结构化元数据。
type FastIPMeta struct {
IP string // 节点 IP
Latency string // 延迟(ms 字符串)
NodeName string // 节点名称(API 返回的 Content 去除前后空白)
}
// FastIPMetaCache 缓存最近一次 FastIP 探测返回的节点元数据。
var FastIPMetaCache FastIPMeta
// SuppressFastIPOutput 为 true 时,GetFastIP 即使 enableOutput=true 也不打印彩色输出。
// MTR 模式在进入备用屏前设置此标志,避免污染主终端历史。
var SuppressFastIPOutput bool
@@ -78,6 +88,13 @@ func GetFastIP(domain string, port string, enableOutput bool) string {
}
//if len(ips) > 0 {
// 填充结构化缓存
FastIPMetaCache = FastIPMeta{
IP: result.IP,
Latency: result.Latency,
NodeName: strings.TrimSpace(result.Content),
}
if enableOutput && !SuppressFastIPOutput {
_, _ = fmt.Fprintf(color.Output, "%s preferred API IP - %s - %s - %s",
color.New(color.FgWhite, color.Bold).Sprintf("[NextTrace API]"),