https://github.com/relvacode/go-namespace
Namespace access for Go values
https://github.com/relvacode/go-namespace
access fields go name namespace reflect string value
Last synced: 3 months ago
JSON representation
Namespace access for Go values
- Host: GitHub
- URL: https://github.com/relvacode/go-namespace
- Owner: relvacode
- Created: 2016-10-18T10:56:49.000Z (over 9 years ago)
- Default Branch: master
- Last Pushed: 2017-05-23T14:29:40.000Z (almost 9 years ago)
- Last Synced: 2024-06-20T10:03:49.293Z (almost 2 years ago)
- Topics: access, fields, go, name, namespace, reflect, string, value
- Language: Go
- Homepage:
- Size: 15.6 KB
- Stars: 1
- Watchers: 3
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
```go
import "github.com/relvacode/go-namespace"
```
[](https://godoc.org/github.com/relvacode/go-namespace)
[](https://travis-ci.org/relvacode/go-namespace)
Go namespace provides the ability to get a Go value by a string name. Similar to `text/template`'s value access without templating.
```go
// l is your value that you want to search its namespace for
// It can be either a struct or map, or an interface to a struct or map.
l := map[string]interface{}{
"PrimaryKey": map[string]interface{}{
"SecondaryKey": "MyValue",
},
}
// Get a value using ordered names.
v, err = namespace.NameSpace(l, []string{"PrimaryKey", "SecondaryKey"})
if err != nil {
// Do something with the error here
}
fmt.Println(v.String()) // Outputs: MyValue
```
### Struct Tags
Using the `ns` struct tag you can change how namespace will access that struct field.
```go
type MyStruct struct {
// Ignore this field as a namespace
Passthough OtherStruct `ns:'-"`
// Rename the namespace name to 'new'
Rename OtherStruct `ns:"new"`
}
```
### `namespace.Value`
`namespace.Value` is a wrapper around `reflect.Value` that provides safe methods for converting objects into a requested native type.
```go
v := namespace.ValueOf(1234.567)
i, err := v.Int()
```