golang提取Go结构体字段名称、类型和标签的插件库textra的使用

Golang提取Go结构体字段名称、类型和标签的插件库textra的使用

Textra是一个零依赖、简单快速的结构体标签解析库。它最初是为另一个私有项目构建的,但后来决定开源,因为它可能对其他人有用。

安装

go get github.com/ravsii/textra

基本使用示例

type Tester struct {
 NoTags   bool
 WithTag  string `json:"with_tag,omitempty"`
 WithTags string `json:"with_tags"          sql:"with_tag"`
 SqlOnly  string `sql:"sql_only"`
}

func main() {
 basic := textra.Extract((*Tester)(nil))
 for _, field := range basic {
  fmt.Println(field)
 }
}

输出结果:

NoTags(bool):[]
WithTag(string):[json:"with_tag,omitempty"]
WithTags(string):[json:"with_tags" sql:"with_tag"]
SqlOnly(string):[sql:"sql_only"]

使用功能方法

移除空标签的字段

removed := basic.RemoveEmpty()
for _, field := range removed {
 fmt.Println(field)
}

输出结果:

WithTag(string):[json:"with_tag,omitempty"]
WithTags(string):[json:"with_tags" sql:"with_tag"]
SqlOnly(string):[sql:"sql_only"]

只获取特定标签的字段

onlySQL := removed.OnlyTag("sql")
for _, field := range onlySQL {
 fmt.Println(field)
}

输出结果:

WithTags(string):sql:"with_tag"
SqlOnly(string):sql:"sql_only"

类型解析示例

Textra还能解析各种类型的字符串表示:

type Types struct {
 intType        int
 intPType       *int
 byteType       byte
 bytePType      *byte
 byteArrType    []byte
 byteArrPType   []*byte
 bytePArrPType  *[]*byte
 runeType       rune
 runePType      *rune
 stringType     string
 stringPType    *string
 booleanType    bool
 booleanPType   *bool
 mapType        map[string]string
 mapPType       map[*string]*string
 mapPImportType map[*string]*time.Time
 chanType       chan int
 funcType       func() error
 funcParamsType func(arg1 int, arg2 string, arg3 map[*string]*time.Time) (int, error)
 importType     time.Time
 pointerType    *string
}

func main() {
 fields := textra.Extract((*Types)(nil))
 for _, field := range fields {
  fmt.Println(field.Name, field.Type)
 }
}

输出结果:

intType int
intPType *int
byteType uint8
bytePType *uint8
byteArrType []uint8
byteArrPType []*uint8
bytePArrPType *[]*uint8
runeType int32
runePType *int32
stringType string
stringPType *string
booleanType bool
booleanPType *bool
mapType map[string]string
mapPType map[*string]*string
mapPImportType map[*string]*time.Time
chanType chan
funcType func() error
funcParamsType func(int, string, map[*string]*time.Time) int, error
importType time.Time
pointerType *string

Textra的API设计类似于标准库中的time包,其中链式函数会创建新值而不是修改它们。


更多关于golang提取Go结构体字段名称、类型和标签的插件库textra的使用的实战教程也可以访问 https://www.itying.com/category-94-b0.html

1 回复

更多关于golang提取Go结构体字段名称、类型和标签的插件库textra的使用的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


使用textra库提取Go结构体字段信息

textra是一个用于提取Go结构体字段名称、类型和标签的轻量级库。它通过反射机制获取结构体信息,并以友好的方式呈现。

安装

go get github.com/tenntenn/textra

基本用法

1. 提取结构体字段信息

package main

import (
	"fmt"
	"github.com/tenntenn/textra"
)

type User struct {
	ID        int64  `json:"id" db:"user_id"`
	Name      string `json:"name" db:"user_name"`
	Email     string `json:"email" db:"user_email"`
	CreatedAt string `json:"created_at" db:"created_at"`
}

func main() {
	fields := textra.Fields(User{})
	for _, f := range fields {
		fmt.Printf("Name: %s\n", f.Name)
		fmt.Printf("Type: %s\n", f.Type)
		fmt.Printf("Tags:\n")
		for _, t := range f.Tags {
			fmt.Printf("  %s: %s\n", t.Key, t.Value)
		}
		fmt.Println("---")
	}
}

输出结果:

Name: ID
Type: int64
Tags:
  json: id
  db: user_id
---
Name: Name
Type: string
Tags:
  json: name
  db: user_name
---
Name: Email
Type: string
Tags:
  json: email
  db: user_email
---
Name: CreatedAt
Type: string
Tags:
  json: created_at
  db: created_at
---

2. 获取特定标签的值

func main() {
	fields := textra.Fields(User{})
	for _, f := range fields {
		jsonTag := f.Tag("json")
		fmt.Printf("Field: %s, JSON tag: %s\n", f.Name, jsonTag)
	}
}

3. 检查标签是否存在

func main() {
	fields := textra.Fields(User{})
	for _, f := range fields {
		if f.HasTag("db") {
			fmt.Printf("%s has db tag\n", f.Name)
		}
	}
}

高级用法

1. 处理嵌套结构体

type Address struct {
	Street string `json:"street"`
	City   string `json:"city"`
}

type Customer struct {
	User    User    `json:"user"`
	Address Address `json:"address"`
}

func main() {
	fields := textra.Fields(Customer{})
	for _, f := range fields {
		fmt.Printf("Name: %s, Type: %s\n", f.Name, f.Type)
	}
}

2. 自定义处理函数

func main() {
	fields := textra.Fields(User{})
	
	// 只处理有db标签的字段
	for _, f := range fields {
		if dbTag := f.Tag("db"); dbTag != "" {
			fmt.Printf("DB column for %s: %s\n", f.Name, dbTag)
		}
	}
}

性能考虑

textra使用反射机制,因此性能不如直接代码生成的方式。如果性能是关键因素,可以考虑使用代码生成工具如stringergo generate

替代方案

如果需要更强大的结构体处理功能,可以考虑以下替代库:

  • reflect标准库(更底层)
  • github.com/fatih/structs(功能更丰富)
  • github.com/go-playground/validator(专注于验证)

textra的优势在于其简单性和专注于标签提取的特定用途。对于大多数获取结构体元信息的场景,它都是一个不错的选择。

希望这个介绍能帮助你使用textra库提取Go结构体信息!

回到顶部