Golang Design Response Struct For API
package main
import (
"encoding/json"
"fmt"
)
type Optional map[string]interface{}
type Problem struct {
Name string
Description string
}
type ProblemResponse struct {
Name string `json:"name"`
Description string `json:"description"`
Optional
}
func (problem *Problem) ToRes() *ProblemResponse {
return &ProblemResponse{
Name: problem.Name,
Description: problem.Description,
}
}
func main() {
problem := Problem{"StackOverflow", "Asking Question"}
problemRes := problem.ToRes()
problemRes.Optional = make(map[string]interface{})
problemRes.Optional["url"] = "https://stackoverflow.com"
Response(*problemRes)
}
func Response(obj interface{}) {
data, _ := json.Marshal(obj)
fmt.Println(string(data))
}
The code above will print
{
"name": "StackOverflow",
"description": "Asking Question",
"Optional": {
"url": "https://stackoverflow.com"
}
}
But what i want is this
{
"name": "StackOverflow",
"description": "Asking Question",
"url": "https://stackoverflow.com"
}
I want in the main function i can append some information to json response. Any solution for this design, it prefer that we don't change Response Function. Thank in advance !!