简体   繁体   English

在 Go 中包装 API Json 响应

[英]Wrap API Json response in Go

I am sorry if this is a silly question because i am very new in Go.如果这是一个愚蠢的问题,我很抱歉,因为我是 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.我在业务逻辑的基础上调用了几个 api,不同类型的响应来像 json 数组,嵌套 json 和单个 json ZA8CFDE6331B49EB2AC666DE6331B49EB2AC66.F68896 i need to wrap a api response that called according to business logic in a common format like:我需要包装一个 api 响应,该响应根据业务逻辑以通用格式调用,例如:

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

i tried some but its not expect output我尝试了一些,但没想到 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. 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{}使用字段Data类型作为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.然后您可以将任何 API 响应类型分配给Data字段并对其进行编组。

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 Output

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

Run the full code here in Playground .Playground中运行完整代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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