dongwopu8210 2016-07-09 02:30
浏览 58

Golang API编码问题

I'm trying to consume JSON apis through golang, but having a terrible time getting the response back. I'm using a sample JSON endpoint http://jsonplaceholder.typicode.com/posts/1 that returns

{
  "userId": 1,
  "id": 1,
  "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
  "body": "quia et suscipit
suscipit recusandae consequuntur expedita et cum
reprehenderit molestiae ut ut quas totam
nostrum rerum est autem sunt rem eveniet architecto"
}

This is my code which comes from this Stack Overflow Answer:

package main

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

type Post struct {
    UserID string
    ID string
    Title string
    Body string
}

func getJson(url string, target interface{}) error {
    r, err := http.Get(url)
    if err != nil {
        return err
    }
    defer r.Body.Close()
    fmt.Println(r)
    return json.NewDecoder(r.Body).Decode(target)
}

func main() {
    post := new(Post) // or &Foo{}
    getJson("http://jsonplaceholder.typicode.com/posts/1", &post)
    println(post.Body)

}

And this is the output:

go run main.go 
&{200 OK 200 HTTP/1.1 1 1 map[Cf-Cache-Status:[HIT] Cf-Ray:[2bf857d2e55e0d91-SJC] Access-Control-Allow-Credentials:[true] Cache-Control:[public, max-age=14400] Expires:[Sat, 09 Jul 2016 06:28:31 GMT] X-Content-Type-Options:[nosniff] Server:[cloudflare-nginx] Date:[Sat, 09 Jul 2016 02:28:31 GMT] Connection:[keep-alive] X-Powered-By:[Express] Etag:[W/"124-yv65LoT2uMHrpn06wNpAcQ"] Content-Type:[application/json; charset=utf-8] Set-Cookie:[__cfduid=d0c4aacaa5db8dc73c59a530f3d7532af1468031311; expires=Sun, 09-Jul-17 02:28:31 GMT; path=/; domain=.typicode.com; HttpOnly] Pragma:[no-cache] Via:[1.1 vegur] Vary:[Accept-Encoding]] 0xc8200ee100 -1 [chunked] false map[] 0xc8200da000 <nil>}

I know the endpoint works. Is this an encoding issue or something else? I'm on Mac OSX 10.11.15.

Thanks

  • 写回答

2条回答 默认 最新

  • duansai1314 2016-07-09 02:45
    关注

    You have error in unmarshal: cannot unmarshal number into Go value of type string if you print error. UserId and Id should be int.

    Please don't ignore error!

    try this code:

    package main
    
    import (
        "encoding/json"
        "fmt"
        "net/http"
    )
    
    type Post struct {
        UserID int
        ID     int
        Title  string
        Body   string
    }
    
    func getJson(url string, target interface{}) error {
        r, err := http.Get(url)
        if err != nil {
            return err
        }
        defer r.Body.Close()
        fmt.Println(r)
        return json.NewDecoder(r.Body).Decode(target)
    }
    
    func main() {
        post := new(Post) // or &Foo{}
        err := getJson("http://jsonplaceholder.typicode.com/posts/1", &post)
        if err != nil {
            panic(err)
        }
    
        println(post.Body)
        fmt.Printf("Post: %+v
    ", post)
    }
    

    Edited: Why can't I print out the contents of the response body and see it in the command line? Is it encoded? Ans: HTTP request or response used to be in a format or encoded defined by the response-header fields.

    The response-body is obtained from the message-body by decoding any Transfer-Encoding that might have been applied to ensure safe and proper transfer of the message.

    If you print: fmt.Println("Header: %#v ", r.Header)
    You will see, Content-Type:[application/json; charset=utf-8] That's why you are decoding with Json. It also could be xml.

    评论

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。