structure: add travis, example and fix of pointer to struct

This commit is contained in:
Fatih Arslan 2014-07-26 17:41:27 +03:00
parent ad2d6e3fe7
commit c8876826eb
4 changed files with 68 additions and 4 deletions

3
.travis.yml Normal file
View File

@ -0,0 +1,3 @@
language: go
go: 1.3

View File

@ -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}
```

View File

@ -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)

View File

@ -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
}