0x5a17ed / stragts

Parse structured Go Structure Field Tags into yet another Structure!

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

stragts

Go module providing a structured value parser for reflect.StructTag.

📦 Installation

$ go get -u github.com/0x5a17ed/stragts@latest 

🤔 Usage

package main

import (
	"fmt"
	"reflect"

	"github.com/0x5a17ed/stragts"
)

type TagStruct struct {
	Index    *string
	Priority *int
}

func HandleStruct(data any) {
	v := reflect.ValueOf(data)
	t := v.Type()
	for i := 0; i < t.NumField(); i++ {
		tag, found := stragts.Lookup(t.Field(i).Tag, "norm")
		if !found {
			continue
		}

		var tagStruct TagStruct
		if err := tag.Fill(&tagStruct); err != nil {
			fmt.Printf("error: %s\n", err)
			continue
		}

		fmt.Println("index:", *tagStruct.Index, "priority:", *tagStruct.Priority)
	}
}

func main() {
	type TaggedStruct struct {
		Name   string `norm:"index=idx_member,priority=2"`
		Number string `norm:"index=idx_member,priority=1"`
	}
	HandleStruct(TaggedStruct{})
}

🥇 Acknowledgments

The design and the implementation are roughly based on the idea and syntax of the lovely github.com/muir/reflectutils module with an implementation based on the amazing text/template/parse. Both projects have been very inspirational.

The only reason for me to write my own module was because reflectutils was missing a few features, and I was always looking for an opportunity to write a lexer.

About

Parse structured Go Structure Field Tags into yet another Structure!

License:BSD 3-Clause "New" or "Revised" License


Languages

Language:Go 100.0%