Skip to content

Commit

Permalink
update README
Browse files Browse the repository at this point in the history
  • Loading branch information
SoulKa committed Nov 28, 2023
1 parent eb24930 commit 061e0d5
Showing 1 changed file with 38 additions and 7 deletions.
45 changes: 38 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
# golymorph [![Pipeline Tests Status](https://github.com/SoulKa/golymorph/actions/workflows/go-test.yaml/badge.svg)](https://github.com/SoulKa/golymorph/actions/workflows/go-test.yaml) [![Godoc](https://godoc.org/github.com/SoulKa/golymorph?status.svg)](https://godoc.org/github.com/SoulKa/golymorph)

The golymorph module enables resolving polymorphic typing at runtime. It's usually used in
conjunction with
JSON parsing and the `mapstructure` module. In fact, this module takes the use case
of `mapstructure` and takes it
a step further by allowing the user to define a custom type resolver function.
conjunction with JSON parsing and the `mapstructure` module. In fact, this module takes the use case
of `mapstructure` a step further by allowing the user to define a custom type resolver.

## Installation

Expand All @@ -14,9 +12,42 @@ Standard `go get`:
go get github.com/SoulKa/golymorph
```

## Usage & Example
## Docs

For usage and examples see the [Godoc](http://godoc.org/github.com/SoulKa/golymorph).
The docs are hosted on [Godoc](http://godoc.org/github.com/SoulKa/golymorph).

## Use Case

Use this module to resolve polymorphic types at runtime. An example would be a struct that contains
a payload field which can be of different struct types not known at compile time:

```go
// the parent type that contains the polymorphic payload
type Event struct {
Timestamp string
Payload any // <-- AlertPayload or PingPayload?
}

// the polymorphic child types
type AlertPayload struct {
Type string
Message string
}
type PingPayload struct {
Type string
Ip string
}
```

If, for example, you have a JSON that you decode into the `Event` struct, it is cumbersome to parse the JSON into a map, look into the `type` field of the `payload` and after that select and parse the map into the correct type at the `payload` field of the `event` struct.
golymorph does exactly this:

1. Look at the value of a defined field anywhere in the given `map` or JSON
2. Find the correct type using the given pairs of `value ==> reflect.Type`
3. Assign the correct type at the given position anywhere in the "parent" struct
4. Fully decode the given JSON or `map`, now with a concrete struct type as `payload`

## Example

```go
package main
Expand Down Expand Up @@ -73,4 +104,4 @@ func main() {
fmt.Printf("event: %+v\n", event)
fmt.Printf("event payload: %T %+v\n", event.Payload, event.Payload.(AlertPayload))
}
```
```

0 comments on commit 061e0d5

Please sign in to comment.