golang tag 之 gomodifytags

前端之家收集整理的这篇文章主要介绍了golang tag 之 gomodifytags前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

链接gomodifytags原文链接

gomodifytags

是go工具,用来修改/更新struct字段的标签tag.使用gomodifytags可以很方便的update/add/delete struct的字段标签。你可以很方便的增加新的标签,更新已经存在的标签或者移除已经存在的标签。也允许你增加和移除标签选项。它的目的在于被编辑器使用,但是也有模式从终端运行它。

默认按照下划线标识的tag.

安装:

@H_502_12@go get github.com/fatih/gomodifytags

写好结构体,如下:

type Server struct {
	Name string
	Port int
	EnableLogs bool
	BaseDomain string
	Credentials struct{
		UserName string
		Password string
	}
}

在goland终端cd到上面的结构体所在的目录,执行以下命令:

gomodifytags -file go_gomodifytags.go -struct Server -add-tags json

默认情况下,每次改变都会被标准输出,因此运行这个命令是安全的并且看到运行的结果。如果你想永久有效,执行以下命令:

$ gomodifytags -file demo.go -struct Server -add-tags json -w

可以同时添加多个tag:

如下指令会同时添加json和xml标签

gomodifytags -file demo.go -struct Server -add-tags json,xml

如果要使用驼峰标识,使用如下命令:

gomodifytags -file demo.go -struct Server -add-tags json -w

那么后面再设置为驼峰标识就会无效了。

可以为每个字段设置静态值:

增加tag可选项:

gomodifytags -file demo.go -struct Server -add-tags json -add-options json=omitempty

注意,如果tag已经存在了,就没必要再用 -add-tags

移除标签和可选项

要移除xml标签,使用如下指令:

gomodifytags -file demo.go -struct Server -remove-tags xml

同时移除多个标签

gomodifytags -file demo.go -struct Server -remove-tags xml,json

一次性移除所有的标签

gomodifytags -file demo.go -struct Server -clear-tags

移除标签可选项:

gomodifytags -file demo.go -struct Server -remove-options json=omitempty

同时移除多个标签可选项:

gomodifytags -file demo.go -struct Server -remove-options json=omitempty,xml=cdata

移除所有的标签可选项:

gomodifytags -file demo.go -struct Server -clear-options


基于line的标签改变

移除某些line的标签

gomodifytags -file demo.go -line 8,11 -clear-tags xml

在特定的某些行增加tag:(在第5行-第7行增加bson标签)

gomodifytags -file demo.go -line 5,7 -add-tags bson


编辑器集成

原文链接:https://www.f2er.com/go/187210.html

猜你在找的Go相关文章