douhuangjian9627 2018-10-09 13:25
浏览 110

解析REST API响应

I am new to golang. I was writing a program to parse the json response of the API: https://httpbin.org/get. I have used the following code to parse the response:

package main

import (
    "encoding/json"
    "fmt"
    "net/http"
    "os"
)

type Headers struct {
    Close  string `json:"Connection"`
    Accept string `json:"Accept"`
}

type apiResponse struct {
    Header Headers `json:"headers"`
    URL    string  `json:"url"`
}

func main() {
    apiRoot := "https://httpbin.org/get"
    req, err := http.NewRequest("GET", apiRoot, nil)
    if err != nil {
        fmt.Println("Couldn't prepare request")
        os.Exit(1)
    }
    response, err := http.DefaultClient.Do(req)
    if err != nil {
        fmt.Println(err)
        os.Exit(1)
    }
    defer response.Body.Close()
    var responseStruct apiResponse
    err = json.NewDecoder(response.Body).Decode(&responseStruct)
    if err != nil {
        fmt.Println(err)
        os.Exit(1)
    }

    fmt.Printf("%v
", responseStruct)
}

When I run this code the output is:

$ go run parse.go
{{close } https://httpbin.org/get}

From the output, as we can see the "Accept" key in json response is not decoded. Why is it so? How can I parse that string from response body?

  • 写回答

2条回答 默认 最新

  • duanci6484 2018-10-09 13:34
    关注

    Your code is doing well but here I think your Accept key does not return from API that's why it's not showing the Accept value. To check the key, value pair of your struct, use the below print method.

    fmt.Printf("%+v
    ", responseStruct)
    

    To overcome from this situation you need to send Accept with request into header before request the API like:

    req.Header.Set("Accept", "value")
    response, err := hc.Do(req)
    if err != nil {
        fmt.Println(err)
        os.Exit(1)
    }
    

    Then you will get the Accept value in decoded struct as :

    {Header:{Accept:value Close:close} URL:https://httpbin.org/get}
    
    评论

报告相同问题?

悬赏问题

  • ¥30 win from 窗口最大最小化,控件放大缩小,闪烁问题
  • ¥20 易康econgnition精度验证
  • ¥15 msix packaging tool打包问题
  • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致