https://github.com/florinutz/remarshal
similar to json.Unmarshal, but more general
https://github.com/florinutz/remarshal
golang pointers regex string struct
Last synced: 5 months ago
JSON representation
similar to json.Unmarshal, but more general
- Host: GitHub
- URL: https://github.com/florinutz/remarshal
- Owner: florinutz
- License: gpl-3.0
- Created: 2017-10-09T10:10:41.000Z (over 8 years ago)
- Default Branch: master
- Last Pushed: 2017-11-03T20:51:23.000Z (over 8 years ago)
- Last Synced: 2025-07-30T01:57:31.852Z (10 months ago)
- Topics: golang, pointers, regex, string, struct
- Language: Go
- Homepage:
- Size: 46.9 KB
- Stars: 1
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# remarshal
[](https://travis-ci.org/florinutz/remarshal) [](https://goreportcard.com/report/github.com/florinutz/remarshal)
[](https://godoc.org/github.com/florinutz/remarshal)
[](https://codecov.io/gh/florinutz/remarshal)
The package looks up for values in a string and then attaches them to an existing struct's fields. It exposes one interface `RegexUnmarshaler`
```go
func Remarshal(text string, v interface{}, splitter interface{}) error
```
The splitter can be one of:
* `*regexp.Regexp`
* `func(string) (map[string]string, error)`
* anything that implements `StringMapper`
```go
type StringMapper interface {
GetStringMap(string) (map[string]string, error)
}
```
## Examples
### regex splitter
```go
v := &struct {
One string `regex_group:"first"`
Two string // regex_group defaults to Two
Three string `regex_group:"Two"` // this takes precedence over Two
Four string `regex_group:"Three"`
}{}
splitter := regexp.MustCompile(`^(?P.*)\|(?P.*)\|(?P.*)\|(?P.*)$`)
err := remarshal.Remarshal("first|second|third|... and so on", v, splitter)
if err != nil {
fmt.Println(err)
}
fmt.Printf("%#v", v)
// Output: &struct { One string "regex_group:\"first\""; Two string; Three string "regex_group:\"Two\""; Four string "regex_group:\"Three\"" }{One:"first", Two:"", Three:"second", Four:"third"}
```
### function splitter
```go
v := &struct{ Host, Port string }{}
splitter := func(s string) (map[string]string, error) {
host, port, _ := net.SplitHostPort(s)
return map[string]string{
"Host": host,
"Port": port,
}, nil
}
err := remarshal.Remarshal("localhost:12345", v, splitter)
if err != nil {
fmt.Println(err)
}
fmt.Printf("%#v", v)
// Output: &struct { Host string; Port string }{Host:"localhost", Port:"12345"}
```
Remarshal returns multiple errors packed into one using the [hashicorp/multierror](https://github.com/hashicorp/go-multierror) package. You can unpack them.