diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 0000000..2405aef --- /dev/null +++ b/.travis.yml @@ -0,0 +1,3 @@ +language: go +go: 1.3 + diff --git a/README.md b/README.md index 1eb3bc4..8b080d3 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,36 @@ -structure +# Structure [![GoDoc](https://godoc.org/github.com/fatih/structure?status.png)](http://godoc.org/github.com/fatih/structure) [![Build Status](https://travis-ci.org/fatih/structure.png)](https://travis-ci.org/fatih/structure) ========= -Utilities for Go structs +Structure contains various utilitis to work with Go structs. + +## Install + +```bash +go get github.com/fatih/structure +``` + +## Examples + +```go +type Server struct { + Name string + ID int32 + Enabled bool +} + +s := &Server{ + Name: "Arslan", + ID: 123456, + Enabled: true, +} + +m, err := ToMap(s) +if err != nil { + panic(err) +} + +fmt.Printf("%#v", m) +// Output: map[string]interface {}{"Name":"Arslan", "ID":123456, "Enabled":true} + +``` + diff --git a/structure.go b/structure.go index 634beb0..2fcf7fa 100644 --- a/structure.go +++ b/structure.go @@ -17,18 +17,18 @@ func ToMap(in interface{}) (map[string]interface{}, error) { out := make(map[string]interface{}) t := reflect.TypeOf(in) + v := reflect.ValueOf(in) // if pointer get the underlying element≤ if t.Kind() == reflect.Ptr { t = t.Elem() + v = v.Elem() } if t.Kind() != reflect.Struct { return nil, ErrNotStruct } - v := reflect.ValueOf(in) - for i := 0; i < t.NumField(); i++ { field := t.Field(i) diff --git a/structure_test.go b/structure_test.go index 6234847..89e0dd5 100644 --- a/structure_test.go +++ b/structure_test.go @@ -1,6 +1,7 @@ package structure import ( + "fmt" "reflect" "testing" ) @@ -82,3 +83,31 @@ func TestToMap_Tag(t *testing.T) { } } + +func ExampleMap() { + type Server struct { + Name string + ID int32 + Enabled bool + } + + s := &Server{ + Name: "Arslan", + ID: 123456, + Enabled: true, + } + + m, err := ToMap(s) + if err != nil { + panic(err) + } + + fmt.Printf("%#v\n", m["Name"]) + fmt.Printf("%#v\n", m["ID"]) + fmt.Printf("%#v\n", m["Enabled"]) + // Output: + // "Arslan" + // 123456 + // true + +}