简体   繁体   中英

Wrap API Json response in Go

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.

You can simply do:

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

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM