from others structs a bit easier

structcopier

Build Status

This package is copy from deepcopier of Ulule team. Due to deepcopier hasn't updated for a long time, I created this repo to fix some bugs and extend some new features. structcopier is meant to make copying of structs to/from others structs a bit easier.

Installation

go get -u github.com/scottish-ep/structcopier

Usage

// Deep copy instance1 into instance2
Copy(instance1).To(instance2)

// Deep copy instance1 into instance2 and passes the following context (which
// is basically a map[string]interface{}) as first argument
// to methods of instance2 that defined the struct tag "context".
Copy(instance1).WithContext(map[string]interface{}{"foo": "bar"}).To(instance2)

// Deep copy instance2 into instance1
Copy(instance1).From(instance2)

// Deep copy instance2 into instance1 and filter some fields
Copy(instance1).Filter(filters).To(instance2)

// Deep copy instance2 into instance1 and passes the following context (which
// is basically a map[string]interface{}) as first argument
// to methods of instance1 that defined the struct tag "context".
Copy(instance1).WithContext(map[string]interface{}{"foo": "bar"}).From(instance2)

Available options for structcopier struct tag:

Option Description
field Field or method name in source instance
context Takes a map[string]interface{} as first argument (for methods)
force Set the value of a sql.Null* field (instead of copying the struct)
filter Ignore some fields when copy

Options example:

type Source struct {
    Name                         string
    SkipMe                       string
    SQLNullStringToSQLNullString sql.NullString
    SQLNullStringToString        sql.NullString

}

func (Source) MethodThatTakesContext(c map[string]interface{}) string {
    return "whatever"
}

type Destination struct {
    FieldWithAnotherNameInSource      string         `structcopier:"field:Name"`
    SkipMe                            string         `structcopier:"skip"`
    MethodThatTakesContext            string         `structcopier:"context"`
    SQLNullStringToSQLNullString      sql.NullString
    SQLNullStringToString             string         `structcopier:"force"`
}

Example:

package main

import (
    "fmt"

    "github.com/scottish-ep/structcopier"
)

// Model
type User struct {
    // Basic string field
    Name  string
    // structcopier supports https://golang.org/pkg/database/sql/driver/#Valuer
    Email sql.NullString
}

func (u *User) MethodThatTakesContext(ctx map[string]interface{}) string {
    // do whatever you want
    return "hello from this method"
}

// Resource
type UserResource struct {
    DisplayName            string `structcopier:"field:Name"`
    SkipMe                 string `structcopier:"skip"`
    MethodThatTakesContext string `structcopier:"context"`
    Email                  string `structcopier:"force"`

}

func main() {
    user := &User{
        Name: "gilles",
        Email: sql.NullString{
            Valid: true,
            String: "[email protected]",
        },
    }

    resource := &UserResource{}
    // copy all fields from user to resource based on struct tag
    structcopier.Copy(user).To(resource)

    // ignore name when copy from user to resource
    filters := map[string]interface{}{
        "fields" : []string{"Name"},
    }
    structcopier.Copy(user).Filter(filters).To(resource)

    // skip
    fmt.Println(resource.DisplayName)
    fmt.Println(resource.Email)
}
Owner
Scottish EP
Love to build things, currently working on blockchain stuff, learning rust and machine learning.
Scottish EP
Similar Resources

πŸ” Share end-to-end encrypted secrets with others via a one-time URL

πŸ” Share end-to-end encrypted secrets with others via a one-time URL

If you use this repo, star it ✨ πŸ” Share end-to-end encrypted secrets with others via a one-time URL Use to securely share API Keys, Signing secrets,

Dec 26, 2022

πŸ” Share end-to-end encrypted secrets with others via a one-time URL

πŸ” Share end-to-end encrypted secrets with others via a one-time URL

If you use this repo, star it ✨ πŸ” Share end-to-end encrypted secrets with others via a one-time URL Use to securely share API Keys, Signing secrets,

Dec 26, 2022

Render helm values-files from others

helm-plugin-render-values The Helm downloader plugin with rendering templated values files Install Use helm CLI to install this plugin: $ helm plugin

Aug 1, 2022

Package implement reading and writing popular playlist formats: PLS, ASX, M3U, XSPF and others.

go-playlist ⚠️ WARNING The API is not stable yet and can change. Package playlist implement reading and writing popular playlist formats: PLS, ASX, M3

Oct 14, 2021

Gofrette is a reverse shell payload developed in Golang that bypasses Windows defender and many others anti-virus.

Gofrette is a reverse shell payload developed in Golang that bypasses Windows defender and many others anti-virus.

Gofrette Gofrette is a reverse shell payload developed in Golang that bypasses Windows defender and many others anti-virus.

Dec 14, 2022

BQB is a lightweight and easy to use query builder that works with sqlite, mysql, mariadb, postgres, and others.

Basic Query Builder Why Simple, lightweight, and fast Supports any and all syntax by the nature of how it works Doesn't require learning special synta

Dec 7, 2022

A version bumper for homebrew formula and others

bumper (go-bumper) go-bumper is a golang CLI app to provide the formula versions bumping operation for Homebrew. We made Bumper because brew bump-form

Dec 16, 2021

others implement usefuls stuff in their free time. I implement an eventstore framework

Eventstore eventstore is a library where I try out new stuff related to an eventstore as a single point of truth. At the moment I'm writing this it's

Nov 10, 2022

GoPostgreSQL - An example usage of PostgreSQL with GO, very simple since the objective is that others can read and learn

GoPostgreSQL - An example usage of PostgreSQL with GO, very simple since the objective is that others can read and learn

GoPostgreSQL - An example usage of PostgreSQL with GO, very simple since the objective is that others can read and learn

Feb 10, 2022

CLi tools helping to forge HTTP smuggling attack and others

CLi tools helping to forge HTTP smuggling attack and others

HTTPCustomHouse CLi tools helping to forge HTTP smuggling attack and others (httpcustomhouse) Analyze smuggled request without interacting with remote

Sep 23, 2022

a go mini version TCP top on UDP for game connections or others.

sanhua sanhua(δΈ‰θŠ±ηŒ«) is kind of cat with black, red and white color. This is a mini version TCP top on UDP, but with out resend lost packet. As we know.

May 31, 2022

Go implementation of BLAKE2 (b) cryptographic hash function (optimized for 64-bit platforms).

Go implementation of BLAKE2b collision-resistant cryptographic hash function created by Jean-Philippe Aumasson, Samuel Neves, Zooko Wilcox-O'Hearn, an

Jul 11, 2022

Optimized bit-level Reader and Writer for Go.

bitio Package bitio provides an optimized bit-level Reader and Writer for Go. You can use Reader.ReadBits() to read arbitrary number of bits from an i

Dec 1, 2022

A little bit of magic for keeping track of the things you have to do.

Be productive. To-do lists are supposed to help you get things done. And I suppose looking through all the stuff you still have to do each time you wa

Jun 1, 2022

Static bit vector structures in Go

teivah/bitvector Overview A bit vector is an array data structure that compactly stores bits. This library is based on 5 static different data structu

Nov 6, 2022

A Go implementation of the 64-bit xxHash algorithm (XXH64)

xxhash xxhash is a Go implementation of the 64-bit xxHash algorithm, XXH64. This is a high-quality hashing algorithm that is much faster than anything

Dec 22, 2022

go/golang: fast bit set Bloom filter

package implements a fast bloom filter with real 'bitset' and JSONMarshal/JSONUnmarshal to store/reload the Bloom filter.

Nov 3, 2022

Bit is a modern Git CLI

Bit is a modern Git CLI

bit is an experimental modernized git CLI built on top of git that provides happy defaults and other niceties: command and flag suggestions to help yo

Dec 28, 2022

A Free 8-Bit Sprite Generator. Create 256 variants from a single template .PNG

A Free 8-Bit Sprite Generator.  Create 256 variants from a single template .PNG

BitSprite A Free 8-Bit Sprite Generator. What? BitSprite is a program that creates variants of an image across total sprite sheet of the resultant ima

Sep 20, 2022
Helpers for making the use of reflection easier

go-xray This is a Golang library with reflection related functions which I use in my different projects. KeyValue This type is used to construct a key

Oct 24, 2022
A collection of small Go utilities to make life easier.

The simplego package provides a collection of Go utilities for common tasks.

Jan 4, 2023
Examples of accepting interfaces and returning structs

Go Interfaces When I started writing tests in Go, I sometimes used interfaces to mock things in tests. Then I discovered that this is not the correct

Dec 27, 2022
Utility to make kubeseal --raw a bit easier.

ks Utility to make kubeseal --raw a bit easier. Building GOOS=windows GOARCH=amd64 go build -o ks-windows-amd64.exe ks.go GOOS=windows GOARCH=386 go b

Aug 19, 2022
Structscanner is a simple library to make going from database queries to structs easier

structscanner is a simple library to make going from database queries to structs easier, while retaining the flexibility of joins and mapping using struct tags.

Oct 17, 2022
K8s-go-structs - All k8s API Go structs

k8s-api go types Why? Its nice to have it all in a single package. . |-- pkg |

Jul 17, 2022
Scalable game server framework with clustering support and client libraries for iOS, Android, Unity and others through the C SDK.

pitaya Pitaya is an simple, fast and lightweight game server framework with clustering support and client libraries for iOS, Android, Unity and others

Jan 2, 2023
Convert struct, slice, array, map or others for Golang

XConv zh-CN XConv is a golang type convertor. It convert any value between types (base type, struct, array, slice, map, etc.) Features Convert between

Dec 8, 2022
⚑️ A dev tool for microservice developers to run local applications and/or forward others from/to Kubernetes SSH or TCP
⚑️ A dev tool for microservice developers to run local applications and/or forward others from/to Kubernetes SSH or TCP

Your new microservice development environment friend. This CLI tool allows you to define a configuration to work with both local applications (Go, Nod

Jan 4, 2023
Router socks. One port socks for all the others.
Router socks. One port socks for all the others.

Router socks The next step after compromising a machine is to enumerate the network behind. Many tools exist to expose a socks port on the attacker's

Dec 13, 2022