Home > OS >  Wrap API Json response in Go
Wrap API Json response in Go

Time:08-11

I am sorry if this is a silly question because i am very new in Go. I am calling couple of apis on the base of business logic, different types of response coming like json array, nest json and single json object. i need to wrap a api response that called according to business logic in a common format like:

{
"data":"api response here",
"statusCode":200
}

i tried some but its not expect output

type Model[T any] struct {
    Data       T
    StatusCode int
}

model := Model[string]{Data: apiResponse, StatusCode: 200}
out, err := json.Marshal(model)

out put of this code is

{
    "Data": "[{\"name\":\"Harry Potter\",\"city\":\"London\"},{\"name\":\"Don Quixote\",\"city\":\"Madrid\"},{\"name\":\"Joan of Arc\",\"city\":\"Paris\"},{\"name\":\"Rosa Park\",\"city\":\"Alabama\"}]",
    "StatusCode": 200
}

issue is actual api response is still in string.i need api response in proper json and also need to make it generic so that any kind of json response map into it.

CodePudding user response:

You can simply do:

result:=map[string]interface{} {
   "data": apiResponse,
   "statusCode": 200,
}
out, err:=json.Marshal(result)

CodePudding user response:

Use type of field Data as an interface{}

type APIResponse struct {
    Data       interface{} `json:"data"`
    StatusCode int         `json:"statusCode"`
}

And then you can assign any API Response type to the Data field and marshal it.

func main() {
    r := []Person{
        {
            Name: "Harry Porter",
            City: "London",
        },
        {
            Name: "Don Quixote",
            City: "Madrid",
        },
    }

    res := APIResponse{
        Data:       r,
        StatusCode: 200,
    }

    resByt, err := json.Marshal(res)
    if err != nil {
        panic(err)
    }

    fmt.Println(string(resByt))
}

Output

{"data":[{"name":"Harry Porter","city":"London"},{"name":"Don Quixote","city":"Madrid"}],"statusCode":200}

Run the full code here in Playground.

  • Related