I have a database that stores JSON, and a server that provides an external API to whereby through an HTTP post, values in this database can be changed. The database is used by different processes internally, and as such have a common naming scheme.
The keys the customer sees are different, but map 1:1 with the keys in the database (there are unexposed keys). For example:
This is in the database:
{ "bit_size": 8, "secret_key": false }
And this is presented to the client:
{ "num_bits": 8 }
The API can change with respect to field names, but the database always has consistent keys.
I have named the fields the same in the struct, with different flags to the json encoder:
type DB struct { NumBits int `json:"bit_size"` Secret bool `json:"secret_key"` } type User struct { NumBits int `json:"num_bits"` }
I'm using encoding/json
to do the Marshal/Unmarshal.
Is reflect
the right tool for this? Is there an easier way since all of the keys are the same? I was thinking some kind of memcpy
(if I kept the user fields in the same order).
Couldn't struct embedding be useful here?
package main import ( "fmt" ) type DB struct { User Secret bool `json:"secret_key"` } type User struct { NumBits int `json:"num_bits"` } func main() { db := DB{User{10}, true} fmt.Printf("Hello, DB: %+v\n", db) fmt.Printf("Hello, DB.NumBits: %+v\n", db.NumBits) fmt.Printf("Hello, User: %+v\n", db.User) }
http://play.golang.org/p/9s4bii3tQ2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With