猿问

在 Go 中从卡夫卡 REST 代理中提取数据

我正在使用卡夫卡的 REST 代理实例来生成和使用消息。使用API获取新消息,但我无法将这些消息转换为Go中的结构模型。例如:


// Get records

req, err := http.NewRequest(http.MethodGet, fmt.Sprintf(FETCH_CONSUMER, URL, GROUP, CONSUMER), nil)

if err != nil {

    panic(err)

}

req.Header.Add("Accept", CONTENT_TYPE)

respRecords, err := client.Do(req)

if err != nil {

    panic(err)

}

defer respRecords.Body.Close()

fmt.Printf("Response %s\n", respRecords.Status)

fmt.Println(respRecords.Body)

recordsBodyResp := bufio.NewScanner(respRecords.Body)


for recordsBodyResp.Scan() {

    fmt.Printf("<--Body %s\n", recordsBodyResp.Text())

    

}

返回的值采用以下格式:


[{"topic":"backward","key":null,"value":{"AdoptionID":"abcd123","IPAddress":"8.8.8.8","Port":"80","Status":"requested"},"partition":0,"offset":7}]

由于它是一个对象数组,因此我想将键“value”的值部分提取到结构中。这就是我陷入困境的地方。


智慧大石
浏览 128回答 1
1回答

哆啦的时光机

您可以创建如下结构:type AutoGenerated []struct {&nbsp; &nbsp; Topic&nbsp; &nbsp; &nbsp;string&nbsp; &nbsp; &nbsp; `json:"topic"`&nbsp; &nbsp; Key&nbsp; &nbsp; &nbsp; &nbsp;interface{} `json:"key"`&nbsp; &nbsp; Value&nbsp; &nbsp; &nbsp;Value&nbsp; &nbsp; &nbsp; &nbsp;`json:"value"`&nbsp; &nbsp; Partition int&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;`json:"partition"`&nbsp; &nbsp; Offset&nbsp; &nbsp; int&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;`json:"offset"`}type Value struct {&nbsp; &nbsp; AdoptionID string `json:"AdoptionID"`&nbsp; &nbsp; IPAddress&nbsp; string `json:"IPAddress"`&nbsp; &nbsp; Port&nbsp; &nbsp; &nbsp; &nbsp;string `json:"Port"`&nbsp; &nbsp; Status&nbsp; &nbsp; &nbsp;string `json:"Status"`}而昂马歇尔在这种结构中。请参阅此示例代码:package mainimport (&nbsp; &nbsp; "fmt"&nbsp; &nbsp; &nbsp; &nbsp; "encoding/json")func main() {type Value struct {&nbsp; &nbsp; AdoptionID string `json:"AdoptionID"`&nbsp; &nbsp; IPAddress&nbsp; string `json:"IPAddress"`&nbsp; &nbsp; Port&nbsp; &nbsp; &nbsp; &nbsp;string `json:"Port"`&nbsp; &nbsp; Status&nbsp; &nbsp; &nbsp;string `json:"Status"`}type AutoGenerated []struct {&nbsp; &nbsp; Topic&nbsp; &nbsp; &nbsp;string&nbsp; &nbsp; &nbsp; `json:"topic"`&nbsp; &nbsp; Key&nbsp; &nbsp; &nbsp; &nbsp;interface{} `json:"key"`&nbsp; &nbsp; Value&nbsp; &nbsp; &nbsp;Value&nbsp; &nbsp; &nbsp; &nbsp;`json:"value"`&nbsp; &nbsp; Partition int&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;`json:"partition"`&nbsp; &nbsp; Offset&nbsp; &nbsp; int&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;`json:"offset"`}&nbsp; &nbsp; byt := []byte(`[{"topic":"backward","key":null,"value":{"AdoptionID":"abcd123","IPAddress":"8.8.8.8","Port":"80","Status":"requested"},"partition":0,"offset":7}]`)&nbsp; &nbsp;var dat AutoGenerated&nbsp; &nbsp;if err := json.Unmarshal(byt, &dat); err != nil {&nbsp; &nbsp; &nbsp; &nbsp; panic(err)&nbsp; &nbsp; }&nbsp; &nbsp; fmt.Printf("%#v", dat)}
随时随地看视频慕课网APP

相关分类

Go
我要回答