https://github.com/wolfogre/gtag
Help you to get golang struct's tags elegantly.
https://github.com/wolfogre/gtag
go golang tag tags
Last synced: 4 months ago
JSON representation
Help you to get golang struct's tags elegantly.
- Host: GitHub
- URL: https://github.com/wolfogre/gtag
- Owner: wolfogre
- License: mit
- Created: 2020-05-01T09:38:27.000Z (over 5 years ago)
- Default Branch: master
- Last Pushed: 2023-11-15T10:32:55.000Z (almost 2 years ago)
- Last Synced: 2025-04-11T01:52:41.658Z (6 months ago)
- Topics: go, golang, tag, tags
- Language: Go
- Homepage: https://blog.wolfogre.com/posts/gtag/
- Size: 399 KB
- Stars: 22
- Watchers: 2
- Forks: 5
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# gtag
[](https://pkg.go.dev/github.com/wolfogre/gtag)
[](https://github.com/wolfogre/gtag/actions)
[](https://codecov.io/gh/wolfogre/gtag)
[](https://goreportcard.com/report/github.com/wolfogre/gtag)
[](https://github.com/wolfogre/gtag/blob/master/go.mod)
[](https://github.com/wolfogre/gtag/releases)Help you to get golang struct's tags elegantly.
## Quick start
### 1. Define your struct
A source file `user.go`:
```go
package tutorialtype User struct {
Id int `bson:"_id"`
Name string `bson:"name"`
Email string `bson:"email"`
}
```## 2. Run gtag
Run
```bash
go run github.com/wolfogre/gtag/cmd/gtag -types User -tags bson .
```and you will get file user_tag.go:
```go
// Code generated by gtag. DO NOT EDIT.
// See: https://github.com/wolfogre/gtag//go:generate go run github.com/wolfogre/gtag/cmd/gtag -types User -tags bson .
package tutorialimport (
"reflect"
"strings"
)var (
// ...
)// UserTags indicate tags of type User
type UserTags struct {
Id string // `bson:"_id"`
Name string // `bson:"name"`
Email string // `bson:"email"`
}// Tags return specified tags of User
func (*User) Tags(tag string, convert ...func(string) string) UserTags {
conv := func(in string) string { return strings.TrimSpace(strings.Split(in, ",")[0]) }
if len(convert) > 0 {
conv = convert[0]
}
if conv == nil {
conv = func(in string) string { return in }
}
return UserTags{
Id: conv(tagOfUserId.Get(tag)),
Name: conv(tagOfUserName.Get(tag)),
Email: conv(tagOfUserEmail.Get(tag)),
}
}// TagsBson is alias of Tags("bson")
func (*User) TagsBson() UserTags {
var v *User
return v.Tags("bson")
}
```## 3. Use it
Now you can use the generated code to get tags elegantly:
```go
// update mongo document
obj := User{}
tags := obj.TagsBson()_, err := collection.UpdateOne(
ctx,
bson.M{tags.Id: id},
bson.M{
"$set", bson.M{
tags.Name: name,
tags.Email: email,
},
},
)
```## Project status
Gtag is beta and is considered feature complete.