tagsvar
is a Go module that generates Go code for managing struct tags. It reads the struct tags from your Go files and generates constants and variables that you can use in your code.
Features
- Generates constants for struct tag names.
- Generates variables for struct tag options.
- Supports custom tag keys.
- Organizes constants and variables by struct and tag key.
Installation
To install tagsvar
, you can use go get
:
go install github.com/go-mods/tagsvar
Usage
This module provides two main commands for managing your struct tags: clean
and gen
.
Clean Command
The clean
command is used to remove all generated code files. This is useful when you want to regenerate all your code files from scratch.
To use the clean
command, navigate to your project directory and run:
tagsvar clean
or if you want to remove the generated code files from a specific directory, you can use the --dir
flag:
tagsvar clean --dir ".testdata" -r -v
Gen Command
The gen
command is used to generate code files. This command reads the struct tags from your Go files and generates constants and variables that you can use in your code.
To use the gen
command, navigate to your project directory and run:
tagsvar gen
This will generate code files for all Go files in your project. The generated files will be placed in the same directory as the original Go files.
or if you want to generate the code files in a specific directory, you can use the --dir
flag:
tagsvar gen --dir ".testdata" -r -v
Example
You can find examples of generated code in the .testdata directory.
author.go
package testdata
// Author is a struct that represents an author
// #tagsvar
type Author struct {
ID int `json:"id" xml:"id" gorm:"id;type:uuid;default:uuid_generate_v4();primary_key"`
Name string `json:"name" xml:"name" gorm:"name;type:varchar(255);not null"`
Email string `json:"email" xml:"email" gorm:"email"`
}
Generated Code
// Code generated by tagsvar. DO NOT EDIT.
package testdata
// File: author.go
// Struct: Author
// Author is a struct that represents an author
const (
// Tag: json
JsonAuthorId = "id"
JsonAuthorName = "name"
JsonAuthorEmail = "email"
// Tag: xml
XmlAuthorId = "id"
XmlAuthorName = "name"
XmlAuthorEmail = "email"
// Tag: gorm
GormAuthorId = "id"
GormAuthorName = "name"
GormAuthorEmail = "email"
)
var (
// Tag: json
// Tag: xml
// Tag: gorm
GormAuthorIdOptions = map[string]any{
"type": "uuid",
"default": "uuid_generate_v4()",
"primary_key": nil,
}
GormAuthorNameOptions = map[string]any{
"type": "varchar(255)",
"not null": nil,
}
)