I’m new to Go and here’s some code that converts one struct to another using the json
package. My inspiration for this code is I want to separate domain knowledge between the front-end and back-end.
For example, a client hits a RESTful endpoint that will return a JSON-encoded Frontend
response. A database search produces a Backend
object. I want to return the database result by converting the Backend
object to a Frontend
object and then have the endpoint return the Frontend
response.
In the example below I have a simple example of just the conversion piece. Is what I’m doing brilliant or horrible?
package main
import (
"encoding/json"
"fmt"
)
type Backend struct {
ID string `json:"id,omitempty"`
Name string `json:"name,omitempty"`
Value int `json:"value,omitempty"`
}
func (b *Backend) String() string {
return fmt.Sprintf("%+v", *b)
}
type Frontend struct {
ErrorCode string `json:"error_code,omitempty"`
Success bool `json:"success,omitempty"`
Name string `json:"name,omitempty"`
Value int `json:"value,omitempty"`
}
func (f *Frontend) String() string {
return fmt.Sprintf("%+v", *f)
}
func convert(from interface{}, to interface{}) {
fmt.Println("From:", from)
bytes, err := json.Marshal(from)
if err != nil {
panic(err)
}
fmt.Println("To (before):", to)
err = json.Unmarshal(bytes, to)
if err != nil {
panic(err)
}
fmt.Println("To (after):", to)
}
func main() {
from := Backend{
ID: "theID",
Name: "theName",
Value: 42,
}
to := Frontend{
ErrorCode: "theErrorCode",
Success: true,
}
convert(from, &to)
fmt.Println("To (finally):", to)
}
Result:
From: {theID theName 42}
To (before): {ErrorCode:theErrorCode Success:true Name: Value:0}
To (after): {ErrorCode:theErrorCode Success:true Name:theName Value:42}
To (finally): {theErrorCode true theName 42}