GithubHelp home page GithubHelp logo

bountylabs / structs Goto Github PK

View Code? Open in Web Editor NEW

This project forked from fatih/structs

0.0 70.0 1.0 153 KB

Utilities for Go structs

Home Page: http://godoc.org/github.com/fatih/structs

License: MIT License

Go 100.00%

structs's Introduction

Structs GoDoc Build Status Coverage Status

Structs contains various utilities to work with Go (Golang) structs. It was initially used by me to convert a struct into a map[string]interface{}. With time I've added other utilities for structs. It's basically a high level package based on primitives from the reflect package. Feel free to add new functions or improve the existing code.

Install

go get github.com/fatih/structs

Usage and Examples

Just like the standard lib strings, bytes and co packages, structs has many global functions to manipulate or organize your struct data. Lets define and declare a struct:

type Server struct {
	Name        string `json:"name,omitempty"`
	ID          int
	Enabled     bool
	users       []string // not exported
	http.Server          // embedded
}

server := &Server{
	Name:    "gopher",
	ID:      123456,
	Enabled: true,
}
// Convert a struct to a map[string]interface{}
// => {"Name":"gopher", "ID":123456, "Enabled":true}
m := structs.Map(server)

// Convert the values of a struct to a []interface{}
// => ["gopher", 123456, true]
v := structs.Values(server)

// Convert the names of a struct to a []string
// (see "Names methods" for more info about fields)
n := structs.Names(server)

// Convert the values of a struct to a []*Field
// (see "Field methods" for more info about fields)
f := structs.Fields(server)

// Return the struct name => "Server"
n := structs.Name(server)

// Check if any field of a struct is initialized or not.
h := structs.HasZero(server)

// Check if all fields of a struct is initialized or not.
z := structs.IsZero(server)

// Check if server is a struct or a pointer to struct
i := structs.IsStruct(server)

Struct methods

The structs functions can be also used as independent methods by creating a new *structs.Struct. This is handy if you want to have more control over the structs (such as retrieving a single Field).

// Create a new struct type:
s := structs.New(server)

m := s.Map()              // Get a map[string]interface{}
v := s.Values()           // Get a []interface{}
f := s.Fields()           // Get a []*Field
n := s.Names()            // Get a []string
f := s.Field(name)        // Get a *Field based on the given field name
f, ok := s.FieldOk(name)  // Get a *Field based on the given field name
n := s.Name()             // Get the struct name
h := s.HasZero()          // Check if any field is initialized
z := s.IsZero()           // Check if all fields are initialized

Field methods

We can easily examine a single Field for more detail. Below you can see how we get and interact with various field methods:

s := structs.New(server)

// Get the Field struct for the "Name" field
name := s.Field("Name")

// Get the underlying value,  value => "gopher"
value := name.Value().(string)

// Set the field's value
name.Set("another gopher")

// Get the field's kind, kind =>  "string"
name.Kind()

// Check if the field is exported or not
if name.IsExported() {
	fmt.Println("Name field is exported")
}

// Check if the value is a zero value, such as "" for string, 0 for int
if !name.IsZero() {
	fmt.Println("Name is initialized")
}

// Check if the field is an anonymous (embedded) field
if !name.IsEmbedded() {
	fmt.Println("Name is not an embedded field")
}

// Get the Field's tag value for tag name "json", tag value => "name,omitempty"
tagValue := name.Tag("json")

Nested structs are supported too:

addrField := s.Field("Server").Field("Addr")

// Get the value for addr
a := addrField.Value().(string)

// Or get all fields
httpServer := s.Field("Server").Fields()

We can also get a slice of Fields from the Struct type to iterate over all fields. This is handy if you wish to examine all fields:

s := structs.New(server)

for _, f := range s.Fields() {
	fmt.Printf("field name: %+v\n", f.Name())

	if f.IsExported() {
		fmt.Printf("value   : %+v\n", f.Value())
		fmt.Printf("is zero : %+v\n", f.IsZero())
	}
}

Credits

License

The MIT License (MIT) - see LICENSE.md for more details

structs's People

Contributors

fatih avatar shawnps avatar nullbus avatar ivajloip avatar miku avatar thedevsaddam avatar ferhatelmas avatar sergeyt avatar smallfish avatar aleksi avatar asdine avatar emret avatar pragmaticcypher avatar kamronbatman avatar kunalpowar avatar mkacmaz avatar roylou avatar davrux avatar marcobeierer avatar n3wtron avatar polaris1119 avatar

Watchers

Logan Hanks avatar Nick Takayama avatar Fabian Cañas avatar  avatar  avatar David McLaughlin avatar bryan bonczek avatar Bill Couch avatar David Snabel-Caunt avatar Justin McDaniel avatar  avatar Sara Beykpour avatar Marc Dassonneville avatar Noah Jorgensen avatar  avatar Rémy avatar Remy DeCausemaker avatar Patrick Nixon avatar Sean F Chan avatar Troy Howard avatar  avatar Pau Tomàs avatar Yi Cheng avatar Jessie avatar Kayvon Beykpour avatar  avatar James Cloos avatar Dylan Griffin avatar moomou avatar Bill  avatar Daniel Wagner-Hall avatar Michael Evans avatar Victor Jolissaint avatar Sorin Cioban avatar  avatar lhbtim avatar David Gil avatar Kris Wilson avatar Nari Shin avatar Cesar Puerta avatar Michael Braun avatar  avatar Richard Plom avatar  avatar Mateusz avatar Justin Anderson avatar  avatar Larry Cao avatar Rosy Tucker avatar Rohit Khansili avatar James Alexander avatar  avatar Pardis Noorzad avatar Raul Hernandez avatar  avatar  avatar David Carr avatar David  avatar Adeel Abbas avatar  avatar Chen-Rui Chou avatar Mia avatar Brandon Au avatar  avatar Daniel Montalvo avatar Jules avatar Erik Novales avatar Sneha Patil avatar  avatar Benjamin Goh avatar

Forkers

classicvalues

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.