This is a Golang library with reflection related functions which I use in my different projects.
This type is used to construct a key-value pair. You can use it as follows:
package main
import (
"fmt"
"github.com/pieterclaerhout/go-xray"
)
func main() {
pair := &xray.KeyValue{
Key: "key",
Value: "value",
}
fmt.Println(pair.String())
// Ouptut: key=value
}
If both Key
and Value
are empty, an empty string is returned.
Name allows you to get the name of an object.
package main
import (
"fmt"
"github.com/pieterclaerhout/go-xray"
)
func main() {
v := &test{}
fmt.Println(xray.Name(v))
// Ouptut: test
n := nil
fmt.Println(xray.Name(n))
// Ouptut: <nil>
}
The function xray.Properties
returns the a list with the property names defined in a struct:
package main
import (
"fmt"
"github.com/pieterclaerhout/go-xray"
)
func main() {
type sampleStruct struct {
Name string `form:"name" json:"name"`
Title string `form:"title" json:"title"`
}
v, _ := xray.Properties(sampleStruct{})
// v now contains:
// []string{
// "Name",
// "Title",
// }
}
The function xray.PropertiesAsMap
does the same, but also includes the values and returns a map[string]interface{}
instance:
package main
import (
"fmt"
"github.com/pieterclaerhout/go-xray"
)
func main() {
type sampleStruct struct {
Name string `form:"name" json:"name"`
Title string `form:"title" json:"title"`
}
v, _ := xray.PropertiesAsMap(sampleStruct{})
// v now contains:
// map[string]interface{}{
// "Name": "name",
// "Title": "title",
// }
}
The function xray.Property
retrieves a single value by it's name:
package main
import (
"fmt"
"github.com/pieterclaerhout/go-xray"
)
func main() {
type sampleStruct struct {
Name string `form:"name" json:"name"`
Title string `form:"title" json:"title"`
}
v, _ := xray.Property(sampleStruct{}, "Name")
// v now contains:
// "name"
}
The xray.Tags
function allows you to easily extract tags from a struct:
package main
import (
"fmt"
"github.com/pieterclaerhout/go-xray"
)
func main() {
type sampleStruct struct {
Name string `form:"name" json:"name"`
Title string `form:"title" json:"title"`
}
v, _ := xray.Tags(sampleStruct{}, "form")
// v now contains:
// map[string]string{
// "Name": "name",
// "Title": "title",
// }
}