github.com/gravitational/teleport/api@v0.0.0-20240507183017-3110591cbafc/utils/conv.go (about) 1 /* 2 Copyright 2015 Gravitational, Inc. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 16 */ 17 18 package utils 19 20 import ( 21 "bytes" 22 "encoding/json" 23 24 "github.com/gravitational/trace" 25 ) 26 27 // ObjectToStruct is converts any structure into JSON and then unmarshalls it into 28 // another structure. 29 // 30 // Teleport configuration uses this (strange, at first) trick to convert from one 31 // struct type to another, if their fields are loosely compatible via their `json` tags 32 // 33 // Example: assume you have two structs: 34 // 35 // type A struct { 36 // Name string `json:"name"` 37 // Age int `json:"age"` 38 // } 39 // 40 // type B struct { 41 // FullName string `json:"name"` 42 // } 43 // 44 // Now you can convert B to A: 45 // 46 // b := &B{ FullName: "Bob Dilan"} 47 // var a *A 48 // utils.ObjectToStruct(b, &a) 49 // fmt.Println(a.Name) 50 // 51 // > "Bob Dilan" 52 func ObjectToStruct(in interface{}, out interface{}) error { 53 bytes, err := json.Marshal(in) 54 if err != nil { 55 return trace.Wrap(err, "failed to marshal %v, %v", in, err) 56 } 57 if err := json.Unmarshal(bytes, out); err != nil { 58 return trace.Wrap(err, "failed to unmarshal %v into %T, %v", in, out, err) 59 } 60 return nil 61 } 62 63 // StrictObjectToStruct converts any structure into JSON and then unmarshalls 64 // it into another structure using a strict decoder. 65 func StrictObjectToStruct(in interface{}, out interface{}) error { 66 data, err := json.Marshal(in) 67 if err != nil { 68 return trace.Wrap(err, "failed to marshal %v, %v", in, err) 69 } 70 71 dec := json.NewDecoder(bytes.NewReader(data)) 72 dec.DisallowUnknownFields() 73 74 if err := dec.Decode(out); err != nil { 75 return trace.Wrap(err, "failed to unmarshal %v into %T, %v", in, out, err) 76 } 77 return nil 78 }