go-graphviz:纯Go实现的Graphviz绑定,无需安装依赖,支持多种布局与格式

Go bindings for Graphviz

分支2Tags24
文件最后提交记录最后更新时间
1 年前
1 年前
1 年前
1 年前
9 个月前
1 年前
1 年前
1 年前
4 年前
1 年前
6 年前
1 年前
9 个月前
1 年前
1 年前
1 年前
1 年前
9 个月前
9 个月前
1 年前
1 年前
1 年前
1 年前

go-graphviz Go GoDoc

Graphviz 的 Go 绑定

特性

Graphviz 版本信息见 此处

  • 纯 Go 库
  • 无需安装 Graphviz 库(无需执行 ~brew install graphviz~ 或 ~apt-get install graphviz~)
    • Graphviz 库已转换为 WebAssembly (WASM) 并嵌入其中,因此可在所有环境中一致运行
  • 支持 DOT 语言的编码与解码
  • 支持用于自定义格式的自定义渲染器
  • 支持以类型安全的方式设置图形属性

支持的布局

circo dot fdp neato nop nop1 nop2 osage patchwork sfdp twopi

支持的格式

dot svg png jpg

以上是默认支持的格式。您也可以添加自定义格式。

安装

$ go get github.com/goccy/go-graphviz

概要

1. 在 Go 中编写 DOT 图形

package main

import (
  "bytes"
  "context"
  "fmt"
  "log"

  "github.com/goccy/go-graphviz"
)

func main() {
  ctx := context.Background()
  g, err := graphviz.New(ctx)
  if err != nil { panic(err )}

  graph, err := g.Graph()
  if err != nil { panic(err) }
  defer func() {
    if err := graph.Close(); err != nil { panic(err) }
    g.Close()
  }()
  n, err := graph.CreateNodeByName("n")
  if err != nil { panic(err) }

  m, err := graph.CreateNodeByName("m")
  if err != nil { panic(err) }

  e, err := graph.CreateEdgeByName("e", n, m)
  if err != nil { panic(err) }
  e.SetLabel("e")

  var buf bytes.Buffer
  if err := g.Render(ctx, graph, "dot", &buf); err != nil {
    log.Fatal(err)
  }
  fmt.Println(buf.String())
}

2. 解析 DOT 图形

path := "/path/to/dot.gv"
b, err := os.ReadFile(path)
if err != nil { panic(err) }
graph, err := graphviz.ParseBytes(b)

3. 渲染图形

ctx := context.Background()
g, err := graphviz.New(ctx)
if err != nil { panic(err) }

graph, err := g.Graph()
if err != nil { panic(err) }

// create your graph

// 1. write encoded PNG data to buffer
var buf bytes.Buffer
if err := g.Render(ctx, graph, graphviz.PNG, &buf); err != nil { panic(err) }

// 2. get as image.Image instance
image, err := g.RenderImage(ctx, graph)
if err != nil { panic(err) }

// 3. write to file directly
if err := g.RenderFilename(ctx, graph, graphviz.PNG, "/path/to/graph.png"); err != nil { panic(err) }

工具

dot

安装

$ go install github.com/goccy/go-graphviz/cmd/dot@latest

使用方法

Usage:
  dot [OPTIONS]

Application Options:
  -T=         specify output format ( currently supported: dot svg png jpg ) (default: dot)
  -K=         specify layout engine ( currently supported: circo dot fdp neato nop nop1 nop2 osage patchwork sfdp twopi )
  -o=         specify output file name

Help Options:
  -h, --help  Show this help message

工作原理

  1. Protocol Buffers 文件 生成 Go 与 C 之间的绑定。
  2. Docker 容器 上构建 graphviz.wasm。
  3. 通过 internal/wasm 包使用子包(cdt cgraph gvc)中的 Graphviz 功能。
  4. graphviz 包为所有子包提供外观接口。

许可证

MIT

本库嵌入并使用 graphviz.wasm,该文件基于 Graphviz 的原始源代码生成。因此,graphviz.wasm 遵循 Graphviz 采用的许可证(Eclipse Public License)。