...

Text file src/dario.cat/mergo/README.md

Documentation: dario.cat/mergo

     1# Mergo
     2
     3[![GitHub release][5]][6]
     4[![GoCard][7]][8]
     5[![Test status][1]][2]
     6[![OpenSSF Scorecard][21]][22]
     7[![OpenSSF Best Practices][19]][20]
     8[![Coverage status][9]][10]
     9[![Sourcegraph][11]][12]
    10[![FOSSA status][13]][14]
    11
    12[![GoDoc][3]][4]
    13[![Become my sponsor][15]][16]
    14[![Tidelift][17]][18]
    15
    16[1]: https://github.com/imdario/mergo/workflows/tests/badge.svg?branch=master
    17[2]: https://github.com/imdario/mergo/actions/workflows/tests.yml
    18[3]: https://godoc.org/github.com/imdario/mergo?status.svg
    19[4]: https://godoc.org/github.com/imdario/mergo
    20[5]: https://img.shields.io/github/release/imdario/mergo.svg
    21[6]: https://github.com/imdario/mergo/releases
    22[7]: https://goreportcard.com/badge/imdario/mergo
    23[8]: https://goreportcard.com/report/github.com/imdario/mergo
    24[9]: https://coveralls.io/repos/github/imdario/mergo/badge.svg?branch=master
    25[10]: https://coveralls.io/github/imdario/mergo?branch=master
    26[11]: https://sourcegraph.com/github.com/imdario/mergo/-/badge.svg
    27[12]: https://sourcegraph.com/github.com/imdario/mergo?badge
    28[13]: https://app.fossa.io/api/projects/git%2Bgithub.com%2Fimdario%2Fmergo.svg?type=shield
    29[14]: https://app.fossa.io/projects/git%2Bgithub.com%2Fimdario%2Fmergo?ref=badge_shield
    30[15]: https://img.shields.io/github/sponsors/imdario
    31[16]: https://github.com/sponsors/imdario
    32[17]: https://tidelift.com/badges/package/go/github.com%2Fimdario%2Fmergo
    33[18]: https://tidelift.com/subscription/pkg/go-github.com-imdario-mergo
    34[19]: https://bestpractices.coreinfrastructure.org/projects/7177/badge
    35[20]: https://bestpractices.coreinfrastructure.org/projects/7177
    36[21]: https://api.securityscorecards.dev/projects/github.com/imdario/mergo/badge
    37[22]: https://api.securityscorecards.dev/projects/github.com/imdario/mergo
    38
    39A helper to merge structs and maps in Golang. Useful for configuration default values, avoiding messy if-statements.
    40
    41Mergo merges same-type structs and maps by setting default values in zero-value fields. Mergo won't merge unexported (private) fields. It will do recursively any exported one. It also won't merge structs inside maps (because they are not addressable using Go reflection).
    42
    43Also a lovely [comune](http://en.wikipedia.org/wiki/Mergo) (municipality) in the Province of Ancona in the Italian region of Marche.
    44
    45## Status
    46
    47It is ready for production use. [It is used in several projects by Docker, Google, The Linux Foundation, VMWare, Shopify, Microsoft, etc](https://github.com/imdario/mergo#mergo-in-the-wild).
    48
    49### Important notes
    50
    51#### 1.0.0
    52
    53In [1.0.0](//github.com/imdario/mergo/releases/tag/1.0.0) Mergo moves to a vanity URL `dario.cat/mergo`.
    54
    55#### 0.3.9
    56
    57Please keep in mind that a problematic PR broke [0.3.9](//github.com/imdario/mergo/releases/tag/0.3.9). I reverted it in [0.3.10](//github.com/imdario/mergo/releases/tag/0.3.10), and I consider it stable but not bug-free. Also, this version adds support for go modules.
    58
    59Keep in mind that in [0.3.2](//github.com/imdario/mergo/releases/tag/0.3.2), Mergo changed `Merge()`and `Map()` signatures to support [transformers](#transformers). I added an optional/variadic argument so that it won't break the existing code.
    60
    61If you were using Mergo before April 6th, 2015, please check your project works as intended after updating your local copy with ```go get -u dario.cat/mergo```. I apologize for any issue caused by its previous behavior and any future bug that Mergo could cause in existing projects after the change (release 0.2.0).
    62
    63### Donations
    64
    65If Mergo is useful to you, consider buying me a coffee, a beer, or making a monthly donation to allow me to keep building great free software. :heart_eyes:
    66
    67<a href='https://ko-fi.com/B0B58839' target='_blank'><img height='36' style='border:0px;height:36px;' src='https://az743702.vo.msecnd.net/cdn/kofi1.png?v=0' border='0' alt='Buy Me a Coffee at ko-fi.com' /></a>
    68<a href="https://liberapay.com/dario/donate"><img alt="Donate using Liberapay" src="https://liberapay.com/assets/widgets/donate.svg"></a>
    69<a href='https://github.com/sponsors/imdario' target='_blank'><img alt="Become my sponsor" src="https://img.shields.io/github/sponsors/imdario?style=for-the-badge" /></a>
    70
    71### Mergo in the wild
    72
    73- [moby/moby](https://github.com/moby/moby)
    74- [kubernetes/kubernetes](https://github.com/kubernetes/kubernetes)
    75- [vmware/dispatch](https://github.com/vmware/dispatch)
    76- [Shopify/themekit](https://github.com/Shopify/themekit)
    77- [imdario/zas](https://github.com/imdario/zas)
    78- [matcornic/hermes](https://github.com/matcornic/hermes)
    79- [OpenBazaar/openbazaar-go](https://github.com/OpenBazaar/openbazaar-go)
    80- [kataras/iris](https://github.com/kataras/iris)
    81- [michaelsauter/crane](https://github.com/michaelsauter/crane)
    82- [go-task/task](https://github.com/go-task/task)
    83- [sensu/uchiwa](https://github.com/sensu/uchiwa)
    84- [ory/hydra](https://github.com/ory/hydra)
    85- [sisatech/vcli](https://github.com/sisatech/vcli)
    86- [dairycart/dairycart](https://github.com/dairycart/dairycart)
    87- [projectcalico/felix](https://github.com/projectcalico/felix)
    88- [resin-os/balena](https://github.com/resin-os/balena)
    89- [go-kivik/kivik](https://github.com/go-kivik/kivik)
    90- [Telefonica/govice](https://github.com/Telefonica/govice)
    91- [supergiant/supergiant](supergiant/supergiant)
    92- [SergeyTsalkov/brooce](https://github.com/SergeyTsalkov/brooce)
    93- [soniah/dnsmadeeasy](https://github.com/soniah/dnsmadeeasy)
    94- [ohsu-comp-bio/funnel](https://github.com/ohsu-comp-bio/funnel)
    95- [EagerIO/Stout](https://github.com/EagerIO/Stout)
    96- [lynndylanhurley/defsynth-api](https://github.com/lynndylanhurley/defsynth-api)
    97- [russross/canvasassignments](https://github.com/russross/canvasassignments)
    98- [rdegges/cryptly-api](https://github.com/rdegges/cryptly-api)
    99- [casualjim/exeggutor](https://github.com/casualjim/exeggutor)
   100- [divshot/gitling](https://github.com/divshot/gitling)
   101- [RWJMurphy/gorl](https://github.com/RWJMurphy/gorl)
   102- [andrerocker/deploy42](https://github.com/andrerocker/deploy42)
   103- [elwinar/rambler](https://github.com/elwinar/rambler)
   104- [tmaiaroto/gopartman](https://github.com/tmaiaroto/gopartman)
   105- [jfbus/impressionist](https://github.com/jfbus/impressionist)
   106- [Jmeyering/zealot](https://github.com/Jmeyering/zealot)
   107- [godep-migrator/rigger-host](https://github.com/godep-migrator/rigger-host)
   108- [Dronevery/MultiwaySwitch-Go](https://github.com/Dronevery/MultiwaySwitch-Go)
   109- [thoas/picfit](https://github.com/thoas/picfit)
   110- [mantasmatelis/whooplist-server](https://github.com/mantasmatelis/whooplist-server)
   111- [jnuthong/item_search](https://github.com/jnuthong/item_search)
   112- [bukalapak/snowboard](https://github.com/bukalapak/snowboard)
   113- [containerssh/containerssh](https://github.com/containerssh/containerssh)
   114- [goreleaser/goreleaser](https://github.com/goreleaser/goreleaser)
   115- [tjpnz/structbot](https://github.com/tjpnz/structbot)
   116
   117## Install
   118
   119    go get dario.cat/mergo
   120
   121    // use in your .go code
   122    import (
   123        "dario.cat/mergo"
   124    )
   125
   126## Usage
   127
   128You can only merge same-type structs with exported fields initialized as zero value of their type and same-types maps. Mergo won't merge unexported (private) fields but will do recursively any exported one. It won't merge empty structs value as [they are zero values](https://golang.org/ref/spec#The_zero_value) too. Also, maps will be merged recursively except for structs inside maps (because they are not addressable using Go reflection).
   129
   130```go
   131if err := mergo.Merge(&dst, src); err != nil {
   132    // ...
   133}
   134```
   135
   136Also, you can merge overwriting values using the transformer `WithOverride`.
   137
   138```go
   139if err := mergo.Merge(&dst, src, mergo.WithOverride); err != nil {
   140    // ...
   141}
   142```
   143
   144Additionally, you can map a `map[string]interface{}` to a struct (and otherwise, from struct to map), following the same restrictions as in `Merge()`. Keys are capitalized to find each corresponding exported field.
   145
   146```go
   147if err := mergo.Map(&dst, srcMap); err != nil {
   148    // ...
   149}
   150```
   151
   152Warning: if you map a struct to map, it won't do it recursively. Don't expect Mergo to map struct members of your struct as `map[string]interface{}`. They will be just assigned as values.
   153
   154Here is a nice example:
   155
   156```go
   157package main
   158
   159import (
   160	"fmt"
   161	"dario.cat/mergo"
   162)
   163
   164type Foo struct {
   165	A string
   166	B int64
   167}
   168
   169func main() {
   170	src := Foo{
   171		A: "one",
   172		B: 2,
   173	}
   174	dest := Foo{
   175		A: "two",
   176	}
   177	mergo.Merge(&dest, src)
   178	fmt.Println(dest)
   179	// Will print
   180	// {two 2}
   181}
   182```
   183
   184Note: if test are failing due missing package, please execute:
   185
   186    go get gopkg.in/yaml.v3
   187
   188### Transformers
   189
   190Transformers allow to merge specific types differently than in the default behavior. In other words, now you can customize how some types are merged. For example, `time.Time` is a struct; it doesn't have zero value but IsZero can return true because it has fields with zero value. How can we merge a non-zero `time.Time`?
   191
   192```go
   193package main
   194
   195import (
   196	"fmt"
   197	"dario.cat/mergo"
   198    "reflect"
   199    "time"
   200)
   201
   202type timeTransformer struct {
   203}
   204
   205func (t timeTransformer) Transformer(typ reflect.Type) func(dst, src reflect.Value) error {
   206	if typ == reflect.TypeOf(time.Time{}) {
   207		return func(dst, src reflect.Value) error {
   208			if dst.CanSet() {
   209				isZero := dst.MethodByName("IsZero")
   210				result := isZero.Call([]reflect.Value{})
   211				if result[0].Bool() {
   212					dst.Set(src)
   213				}
   214			}
   215			return nil
   216		}
   217	}
   218	return nil
   219}
   220
   221type Snapshot struct {
   222	Time time.Time
   223	// ...
   224}
   225
   226func main() {
   227	src := Snapshot{time.Now()}
   228	dest := Snapshot{}
   229	mergo.Merge(&dest, src, mergo.WithTransformers(timeTransformer{}))
   230	fmt.Println(dest)
   231	// Will print
   232	// { 2018-01-12 01:15:00 +0000 UTC m=+0.000000001 }
   233}
   234```
   235
   236## Contact me
   237
   238If I can help you, you have an idea or you are using Mergo in your projects, don't hesitate to drop me a line (or a pull request): [@im_dario](https://twitter.com/im_dario)
   239
   240## About
   241
   242Written by [Dario Castañé](http://dario.im).
   243
   244## License
   245
   246[BSD 3-Clause](http://opensource.org/licenses/BSD-3-Clause) license, as [Go language](http://golang.org/LICENSE).
   247
   248[![FOSSA Status](https://app.fossa.io/api/projects/git%2Bgithub.com%2Fimdario%2Fmergo.svg?type=large)](https://app.fossa.io/projects/git%2Bgithub.com%2Fimdario%2Fmergo?ref=badge_large)

View as plain text