phith0n / goattribute

goattribute is a lightweight Go library that allows you to set (and get) attributes of a struct dynamically, using dot notation (e.g., `a.b.c`).

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Deprecated: use https://github.com/jmespath/go-jmespath instead

goattribute

goattribute is a lightweight Go library that allows you to set (and get) attributes of a struct dynamically, using dot notation (e.g., a.b.c). This can be particularly useful when dealing with dynamic or runtime configuration settings, JSON manipulation, or other similar use cases.

Although most of the code for this project is generated by GPT4, it has full unit tests and can be used safely.

Features

  • Set and get attributes of a struct using dot notation
  • Supports nested structs and pointer types
  • Easy to use with a clean and simple API

Installation

To install goattribute, use go get:

go get github.com/phith0n/goattribute

Usage

Here is a simple example of how to use goattribute:

package main

import (
	"encoding/json"
	"fmt"
	
	"github.com/phith0n/goattribute"
)

type inputTestStruct struct {
	Std  int8   `json:"std" yaml:"std"`
	Name string `json:"name" yaml:"name"`
}

type outputTestStruct struct {
	Filename string `json:"filename" yaml:"filename"`
}

type configTestStruct struct {
	Name   string             `json:"name" yaml:"name"`
	Input  *inputTestStruct   `json:"input" yaml:"input"`
	Output []outputTestStruct `json:"output" yaml:"output"`
}

func main() {
	var config = configTestStruct{
		Input: &inputTestStruct{},
		Output: []outputTestStruct{{Filename: "placeholder"}},
	}
	var attr = goattribute.New(&config)
	attr.SetAttr("Name", "hello")
	attr.SetAttr("Input.Name", "world")
	attr.SetAttr("Input.Std", 2)
	attr.SetAttr("Output[0].Filename", "test.txt")

	data, _ := json.Marshal(attr.GetObject())
	fmt.Println(string(data))
}

Output will be:

{"name":"hello","input":{"std":2,"name":"world"},"output":[{"filename":"test.txt"}]}

Struct tag is also supported:

var attr = goattribute.NewWithTag(&config, "json")
attr.SetAttr("input.name", "tag support")

Caveats

The library uses Go's reflection (reflect package) to manipulate the struct fields. Therefore, the performance might not be as good as direct field access. Please be cautious when using this library in performance-critical applications.

Currently, the library does not support slice or map types for attributes. Support for these types might be added in future releases.

This project will convert int-based variable automatically, take care of the accuracy and range by yourself.

License

goattribute is released under the MIT License. See the LICENSE file for more information.

About

goattribute is a lightweight Go library that allows you to set (and get) attributes of a struct dynamically, using dot notation (e.g., `a.b.c`).

License:MIT License


Languages

Language:Go 100.0%