Skip to content
/ gtag Public
forked from wolfogre/gtag

Help you to get golang struct's tags elegantly.

License

Notifications You must be signed in to change notification settings

fearfate/gtag

 
 

Repository files navigation

gtag

gtag logo

Build Status codecov Go Report Card GitHub go.mod Go version GitHub tag (latest by date)

Help you to get golang struct's tags elegantly.

Installing

Install gtag by running:

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:

package tutorial

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

2. run gtag

Run

gtag -types User -tags bson .

and you will get file user_tag.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"
	"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:

// 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.

About

Help you to get golang struct's tags elegantly.

Resources

License

Stars

Watchers

Forks

Packages

 
 
 

Languages

  • Go 100.0%