这个Go可视化工具,能帮你把项目代码结构和依赖画出来

在性能调优的时候通过pprof 把调用栈可视化成调用图这个我们都见过,那么把 Go 的项目的代码分层结构和依赖都可视化成流程图,这个功能你见过吗,咋一听起来有点像说梦话,不过还真有现成的三方库可以实现这个功能,今天就跟大家分享一个可视化项目的结构和依赖的三方库。文章内容转载自公众号「Go夜读」。

embedded-struct-visualizer

该工具通过扫描 Go 代码所在目录,然后将 Go 代码层次结构可视化。这对于复杂项目的数据结构或识别特定结构的依赖关系非常有用。

使用方法

安装 embedded-struct-visualizer

$ go install github.com/davidschlachter/embedded-struct-visualizer@latest

我默认大家已经安装好 go 环境了 😁

embedded-struct-visualizer[1] 的用法:

执行下面的命令:

$ embedded-struct-visualizer -out demo.gv .
Usage: embedded-struct-visualizer [OPTIONS] DirToScan
If the directory to scan is not provided, it defaults to './'
OPTIONS:
  -out <file>  path to output file (default: write to stdout)
  -v           verbose logging

实操

main.go 代码文件:

package main

import (
 "time"
 "domain.tld/user"
)

type A struct {
 B
 C map[string]D
}

type B struct {
 E, F  string
 G     user.Status
 Timer H
}

type D struct {
 I uint64
}

type H struct {
 Timer time.Ticker
 J     chan D
}

我们通过 embedded-struct-visualizer 生成的 Go 结构关系如下:

digraph {
"main.A" -> { "main.D" "main.B" };
"main.B" -> { "user.Status" "main.H" };
"main.H" -> { "main.D" "time.Ticker" };
}

这个看起来并不美观,那只是我们打开的姿势不对。这里需要用到 graphviz 。

首先你要确保你安装了 graphviz ,安装方法很简单(Mac) brew install graphviz 。

其他环境,可参考官网安装:https://graphviz.org/download/[2]

安装成功之后,我们就可以使用命令 dot -Tps fancy.gv -o fancy.ps ,生成 ps 文件,然后使用 Mac 自带 Preview 即可打开。

e50413bc5d60d8269aee3149b0749d3c.png

如果你还想对层次图上的对象做一些美化,那你可以再了解一下 graphviz guide[3]。

稍微复杂的一个示例 fancy.ps

digraph G {
 size ="4,4";
 main [shape=box]; /* this is a comment */
 main -> parse [weight=8];
 parse -> execute;
 main -> init [style=dotted];
 main -> cleanup;
 execute -> { make_string; printf}
 init -> make_string;
 edge [color=red]; // so is this
 main -> printf [style=bold,label="100 times"];
 make_string [label="make a\nstring"];
 node [shape=box,style=filled,color=".7 .3 1.0"];
 execute -> compare;
}

执行命令:dot -Tps fancy.gv -o fancy.ps,即可得到如下图:

c61971a18ab7425d3c7490af987c8266.png
图片

📢 注: 如果你指定的字体找不到,可能会报以下错误:Converting the PostScript file “fancy.ps” produced the following warnings: · Handlee not found, using Courier. 其他 graphviz example https://sketchviz.com/graphviz-examples

引用链接

[1] embedded-struct-visualizer: https://github.com/davidschlachter/embedded-struct-visualizer

[2] https://graphviz.org/download/: https://graphviz.org/download/

[3] graphviz guide: https://www.graphviz.org/pdf/dotguide.pdf

- END -

扫码关注公众号「网管叨bi叨」

给网管个星标,第一时间吸我的知识 👆

网管整理了一本《Go 开发参考书》收集了70多条开发实践。去公众号回复【gocookbook】领取!还有一本《k8s 入门实践》讲解了常用软件在K8s上的部署过程,公众号回复【k8s】即可领取!

觉得有用就点个在看  👇👇👇

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值