Skip to content

Commit

Permalink
Merge pull request #16 from wolfogre/dev
Browse files Browse the repository at this point in the history
docs: complate README.md
  • Loading branch information
wolfogre authored May 9, 2020
2 parents 1674620 + 59d3486 commit 395175d
Show file tree
Hide file tree
Showing 3 changed files with 143 additions and 1 deletion.
94 changes: 93 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,96 @@
[![GitHub go.mod Go version](https://img.shields.io/github/go-mod/go-version/wolfogre/gtag)](https://github.com/wolfogre/gtag/blob/master/go.mod)
[![GitHub tag (latest by date)](https://img.shields.io/github/v/tag/wolfogre/gtag)](https://github.com/wolfogre/gtag/releases)

\[WIP\] Get field tag in an elegant way.
Help you to get golang struct's tags elegantly.

## Installing

Install gtag by running:

```bash
go get -u github.com/wolfogre/gtag/cmd/gtag
```

and ensuring that `$GOPATH/bin` is added to your `$PATH`.

## Tutorial

### 1. define your struct

A source file `user.go`:

```go
package tutorial

type User struct {
Id int `bson:"_id"`
Name string `bson:"name"`
Email string `bson:"email"`
}
```

## 2. run gtag

Run

```bash
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 gtag -types User -tags bson .
package tutorial

import "reflect"

var (
// ...
)

type UserTags struct {
Id string
Name string
Email string
}

func (User) Tags(tag string) UserTags {
return UserTags{
Id: tagOfUserId.Get(tag),
Name: tagOfUserName.Get(tag),
Email: tagOfUserEmail.Get(tag),
}
}

func (v User) TagsBson() UserTags {
return v.Tags("bson")
}
```

## 3. use it

Now you can use the generated code to get tags elegantly:

```go
// update mongo document
tags := User{}.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.
8 changes: 8 additions & 0 deletions test/internal/tutorial/user.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
// user.go
package tutorial

type User struct {
Id int `bson:"_id"`
Name string `bson:"name"`
Email string `bson:"email"`
}
42 changes: 42 additions & 0 deletions test/internal/tutorial/user_tag.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit 395175d

Please sign in to comment.