structReflect.go
package utils
import (
"reflect"
"regexp"
)
// GetStructTagName 获取struct的field的tag内容
func GetStructTagName(i interface{}, fieldName string) []string {
types := reflect.TypeOf(i)
numField := types.Elem().NumField()
var tagValues = make([]string, numField)
for i := 0; i < numField; i++ {
tagValue := types.Elem().Field(i).Tag.Get(fieldName)
if tagValue == "" {
continue
}
tagValues[i] = tagValue
}
return tagValues
}
// GetStructTagNameRegex 获取struct的field的tag内容,并使用regexp
func GetStructTagNameRegex(i interface{}, fieldName string, regStr string) []string {
reg := regexp.MustCompile(regStr)
types := reflect.TypeOf(i)
numField := types.Elem().NumField()
var tagValues = make([]string, numField)
for i := 0; i < numField; i++ {
tagValue := types.Elem().Field(i).Tag.Get(fieldName)
if tagValue == "" {
continue
}
matchArr := reg.FindStringSubmatch(tagValue)
tagValues[i] = matchArr[len(matchArr)-1]
}
return tagValues
}
直接使用如下:
s := S{}
//获取JSON字段的内容
GetStructTagName(&s,"json")
//获取gorm字段的内容
GetStructTagNameRegex(&s,"gorm",`comment:'(.*?)'`)
继承使用如下:
constant.go
package utils
const (
REGEX_COMMENT_VALUE = `comment:'(.*?)'`
FIELD_JSON_VALUE = "json"
FIELD_GORM_VALUE = "gorm"
)
baseModel.go
package model
import (
"utils"
)
type IBaseModel interface {
GetJsonName() []string
GetCommentName() []string
}
type BaseModel struct {
I interface{}
}
// GetJsonName 获取struct的数据库中的名称JsonName
func (b BaseModel) GetJsonName() []string {
return utils.GetStructTagName(b.I, utils.FIELD_JSON_VALUE)
}
// GetCommentName 获取struct的中文名称CommentName
func (b BaseModel) GetCommentName() []string {
return utils.GetStructTagNameRegex(b.I, utils.FIELD_GORM_VALUE, utils.REGEX_COMMENT_VALUE)
}
exampleModel.go
package model
import (
"model"
)
type ExampleModel struct {
Model model.BaseModel
Code string `json:"code" gorm:"primaryKey;type:varchar(10);comment:'代码'"`
Date string `json:"date" gorm:"type:varchar(8);comment:'日期'"`
}
func NewExampleModel() *ExampleModel {
return &ExampleModel{Model: model.BaseModel{I: &ExampleModel{}}}
}
excampleTest.go
package test
import (
"fmt"
"model"
"testing"
)
func TestModel(t *testing.T) {
excample :=model.NewExcampleModel()
jsonName := excample.Model.GetJsonName()
commentName := excample.Model.GetCommentName()
fmt.Println(jsonName,commentName)