structure: add travis, example and fix of pointer to struct
This commit is contained in:
parent
ad2d6e3fe7
commit
c8876826eb
3
.travis.yml
Normal file
3
.travis.yml
Normal file
@ -0,0 +1,3 @@
|
||||
language: go
|
||||
go: 1.3
|
||||
|
||||
36
README.md
36
README.md
@ -1,4 +1,36 @@
|
||||
structure
|
||||
# Structure [](http://godoc.org/github.com/fatih/structure) [](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}
|
||||
|
||||
```
|
||||
|
||||
|
||||
@ -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)
|
||||
|
||||
|
||||
@ -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
|
||||
|
||||
}
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user