/* * Copyright (c) 2020 Alex aka mailoman * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @author Alex aka mailoman * @copyright Copyright (c) 2020 Alex aka mailoman * @since 14.01.2020 * */ package main import ( "encoding/json" "log" "github.com/go-convert/fields" ) type fromStructCustom struct { ID string `copy:"new,update"` Field1 string `copy:"new,update"` Field2 string `copy:"update"` Field3 string `copy:"category-1,ignore"` Field4 string `copy:"category-1,noempty"` } type toStruct struct { ID string Field1 string Field2 string Field3 string Field4 string } func main() { fields.SetTagName("copy") fields.SetOmitTagName("ignore") fields.SetOmitEmptyTagName("noempty") log.Print("example 2.1 - new") from := fromStructCustom{ "1", "field 1 value", "field 2 value", "omitting", "not empty", } to := toStruct{ "old val 1", "old field 1 value", "old field 2 value", "old field 3 value", "old field 4 value", } fields.Сonvert(from, "new", &to) fromB, _ := json.Marshal(from) toB, _ := json.Marshal(to) log.Printf("from %s => to %s", string(fromB), string(toB)) log.Print("example 2.2.1 - category-1") from = fromStructCustom{ "1", "field 1 value", "field 2 value", "omitting", "not empty", } to = toStruct{ "old val 1", "old field 1 value", "old field 2 value", "old field 3 value", "old field 4 value", } fields.Сonvert(from, "category-1", &to) fromB, _ = json.Marshal(from) toB, _ = json.Marshal(to) log.Printf("from %s => to %s", string(fromB), string(toB)) log.Print("example 2.2.2 - category-1") from = fromStructCustom{ "1", "field 1 value", "field 2 value", "omitting", "", } to = toStruct{ "old val 1", "old field 1 value", "old field 2 value", "old field 3 value", "old field 4 value", } fields.Сonvert(from, "category-1", &to) fromB, _ = json.Marshal(from) toB, _ = json.Marshal(to) log.Printf("from %s => to %s", string(fromB), string(toB)) }