Skip to content

Commit

Permalink
add readme contents
Browse files Browse the repository at this point in the history
  • Loading branch information
awalterschulze committed Jan 23, 2025
1 parent 5f993ac commit 666b237
Showing 1 changed file with 56 additions and 0 deletions.
56 changes: 56 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,59 @@
## parser-go-reflect

Reflection based parser for Go.

We can dynamically walk over reflecting Go `structs` using the [Parser interface](https://github.com/katydid/parser-go):

```go
import (
"reflect"
"io"

reflectparser "github.com/katydid/parser-go-reflect/reflect"
)

func main() {
reflectParser := reflectparser.NewReflectParser()
s := &MyStruct{MyField: "myvalue", OtherField: "othervalue"}
v := reflect.ValueOf(s)
reflectParser.Init(v)
myvalue, err := GetMyField("MyField")
if err != nil {
panic(err)
}
println(myvalue)
}
```

We can then use the parser to decode only `MyField` and skip over other fields and return `"myvalue"`:

```go
func GetMyField(p parser.Interface) (string, error) {
for {
if err := p.Next(); err != nil {
if err == io.EOF {
break
} else {
return "", err
}
}
fieldName, err := p.String()
if err != nil {
return "", err
}
if fieldName != "MyField" {
continue
}
p.Down()
if err := p.Next(); err != nil {
if err == io.EOF {
break
} else {
return "", err
}
}
return p.String()
}
return "", nil
}
```

0 comments on commit 666b237

Please sign in to comment.