Golang library to act on structure fields at runtime. Similar to Python getattr(), setattr(), hasattr() APIs.

Builds Go Report Card codecov.io Go Reference

go-attr

Golang library to act on structure fields at runtime. Similar to Python getattr(), setattr(), hasattr() APIs.

This package provides user friendly helper APIs built on top of the Golang "reflect" library. Reflect library is tricky to use due to its low level nature and results in a panic if an incorrect input is provided. This package provides high level abstractions on such tricky APIs in a user friendly manner.

Installation

go get -u github.com/ssrathi/go-attr

Or install manually

git clone https://github.com/ssrathi/go-attr
cd go-attr
go install

Usage

See full documentation at https://pkg.go.dev/github.com/ssrathi/go-attr.

  import attr "github.com/ssrathi/go-attr"

  type User struct {
    Username string `json:"username" db:"uname"`
    Age      int    `json:"age" meta:"important"`
    password string
  }
  
  user := User{"srathi", 30, "my_secret_123"}
  // NOTE:  Handle error if present in the examples below.
  // Also, all the APIs work on the exported (public) fields of a struct.

SetValue()

Set a new value to an existing field of a struct object.

  // Struct must be passed by pointer to set its field.
  err = attr.SetValue(&user, "Username", "new-username")
  fmt.Printf("New username: %s\n", user.Username)

GetValue()

Get the current value of a struct object.

  val, err = attr.GetValue(&user, "Username")
  fmt.Printf("Username: %s\n", user.Username)

Has()

Check if a field name is part of a struct object.

  ok, err := attr.Has(&user, "FirstName")
  fmt.Printf("FirstName found: %v\n", ok)

Names()

Get the names of all the struct fields.

  fieldNames, err := attr.Names(&user)
  fmt.Printf("field names: %v\n", fieldNames)

Values()

Get the values of all the struct fields.

  fieldValues, err := attr.Values(&user)
  for name, val := range fieldValues {
    fmt.Printf("%s: %v\n", name, val)
  }

GetTag()

Get the value of a specific tag of a specific field in a struct.

  tagValue, err := attr.GetTag(&user, "Age", "meta")
  fmt.Printf("'meta' tag value of 'Age': %s\n", tagValue)

Tags()

Get the value of specific tag from all the public fields of a struct.

  // Tag value is blank ("") if it is not part of a public field.
  tagVals, err := attr.Tags(&user, "json")
  for fieldName, tagVal := range tagVals {
    fmt.Printf("%s: %v\n", fieldName, tagVal)
  }

GetKind()

Get the "kind" (type) of a specified struct field.

  // For example, "var Age int" is of kind 'int'.
  kind, err := attr.GetKind(&user, "Age")
  fmt.Printf("Kind of 'Age': %s\n", kind)

Kinds()

Get the "kind" (type) of all the struct fields.

  // For example, "var Age int" is of kind 'int'.
  kinds, err := attr.Kinds(&user)
  for name, kind := range kinds {
    fmt.Printf("%s: %s\n", name, kind)
  }

Contributing

Contributions are most welcome! Please follow the steps below to send pull requests with your changes.

  • Fork this repository and create a feature branch in it.
  • Push a commit with your changes.
  • Create a new pull request.
  • Create a new issue and link the pull request to it.
Owner
Shyamsunder Rathi
Sr. Manager of Engineering at Nutanix
Shyamsunder Rathi
Similar Resources

A library for diffing golang structures

Diff A library for diffing golang structures and values. Utilizing field tags and reflection, it is able to compare two structures of the same type an

Dec 29, 2022

A well tested and comprehensive Golang statistics library package with no dependencies.

Stats - Golang Statistics Package A well tested and comprehensive Golang statistics library / package / module with no dependencies. If you have any s

Dec 30, 2022

go-sundheit:A library built to provide support for defining service health for golang services

go-sundheit:A library built to provide support for defining service health for golang services

A library built to provide support for defining service health for golang services. It allows you to register async health checks for your dependencies and the service itself, and provides a health endpoint that exposes their status.

Dec 27, 2022

Cogger is a standalone binary and a golang library that reads an internally tiled geotiff

Cogger is a standalone binary and a golang library that reads an internally tiled geotiff (optionally with overviews and masks) and rewrites it

Dec 12, 2022

GoLang port of Google's libphonenumber library

phonenumbers golang port of Google's libphonenumber, forked from libphonenumber from ttacon which in turn is a port of the original Java library. You

Jan 4, 2023

A concurrent rate limiter library for Golang based on Sliding-Window rate limiter algorithm.

ratelimiter A generic concurrent rate limiter library for Golang based on Sliding-window rate limitng algorithm. The implementation of rate-limiter al

Jan 6, 2023

MNA - stands for mobile number assignment - a small zero external dependency golang library that is used to identify mobile number assignment in tanzania

MNA - stands for mobile number assignment - a small zero external dependency golang library that is used to identify mobile number assignment in tanzania

Nov 29, 2021

Easy to use, light enough, good performance Golang library

 Easy to use, light enough, good performance Golang library

指令使用 特性 简单易用、足够轻量,避免过多的外部依赖,最低兼容 Window 7 等老系统 快速上手 安装 $ go get github.com/sohaha/zlsgo HTTP 服务 // main.go

Dec 29, 2022

GoDynamic can load and run Golang dynamic library compiled by -buildmode=shared -linkshared

GoDynamic can load and run Golang dynamic library compiled by -buildmode=shared -linkshared How does it work? GoDynamic works like a dynamic

Sep 30, 2022
Comments
  • SetValue giving type mismatch error for interfaces

    SetValue giving type mismatch error for interfaces

    Code at line 103: if fieldValue.Type() != reflect.TypeOf(newValue) { return ErrMismatchValue }

    This code fails if fieldValue.Type() is an interface, and newValue is a struct/pointer to struct implementing that interface

Identify containers at runtime and observe them. No container runtime required. Read only access to the kernel.

Linux Telemetry The Double Slit Experiment Taken from an interesting physics anomaly where the behavior of a physical system mutates simply by being o

Sep 18, 2022
A Golang and Python solution for Queue-it's Proof-of-Work challenge.

Queue-it Proof-of-Work A Golang and Python solution for Queue-it's Proof-of-Work challenge (https://queue-it.com/blog/proof-of-work-block-bad-bots/).

Oct 16, 2022
Timeboundmap - A Map data structure with expiration cleanup

timeboundmap A Map data structure with expiration cleanup Benchmark goos: darwin

Feb 23, 2022
Minict is a minimal container runtime written in Go.

Minict Minict is a minimal container runtime written in Go. It was made mainly for learning purposes and is intended to be as simple as possible.

Oct 31, 2022
A Runtime Struct Builder for Go

A Runtime Struct Builder for Go

Jul 8, 2022
reflect api without runtime reflect.Value cost

reflect2 reflect api that avoids runtime reflect.Value cost reflect get/set interface{}, with type checking reflect get/set unsafe.Pointer, without ty

Jan 4, 2023
Extremely flexible golang deep comparison, extends the go testing package, tests HTTP APIs and provides tests suite
Extremely flexible golang deep comparison, extends the go testing package, tests HTTP APIs and provides tests suite

go-testdeep Extremely flexible golang deep comparison, extends the go testing package. Latest news Synopsis Description Installation Functions Availab

Jan 5, 2023
Goridge is high performance PHP-to-Golang codec library which works over native PHP sockets and Golang net/rpc package.
Goridge is high performance PHP-to-Golang codec library which works over native PHP sockets and Golang net/rpc package.

Goridge is high performance PHP-to-Golang codec library which works over native PHP sockets and Golang net/rpc package. The library allows you to call Go service methods from PHP with a minimal footprint, structures and []byte support.

Dec 28, 2022
Govalid is a data validation library that can validate most data types supported by golang

Govalid is a data validation library that can validate most data types supported by golang. Custom validators can be used where the supplied ones are not enough.

Apr 22, 2022
A Go (golang) library for parsing and verifying versions and version constraints.

go-version is a library for parsing versions and version constraints, and verifying versions against a set of constraints. go-version can sort a collection of versions properly, handles prerelease/beta versions, can increment versions, etc.

Jan 9, 2023