dpwtr666638 2017-10-15 22:51
浏览 95
已采纳

在Golang中打印解码的JSON

I am very new to Go / programming in general - having just picked it up whilst messing about creating my own crypto currency portfolio web site.

I am struggling printing to the web server output. If I used Printf - it prints to console but as soon as I use Fprintf to print to the web app, I get a number of errors which I can't seem to solve.

Could someone walk me through it?

package main

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

type Obsidian []struct {
    PriceUsd         string `json:"price_usd"`
    PriceBtc         string `json:"price_btc"`
}

func webserver(w http.ResponseWriter, r *http.Request) {
    url := "https://api.coinmarketcap.com/v1/ticker/obsidian/"

    req, err := http.NewRequest("GET", url, nil)
    if err != nil {
            log.Fatal("NewRequest: ", err)
            return
    }

    client := &http.Client{}

    resp, err := client.Do(req)
    if err != nil {
            log.Fatal("Do: ", err)
            return
    }
    defer resp.Body.Close()

    var record Obsidian
    if err := json.NewDecoder(resp.Body).Decode(&record); err != nil {
            log.Println(err)
    }

    fmt.Printf("%+v", record)
}

func main() {
    http.HandleFunc("/test", webserver)
    http.ListenAndServe(":8001", nil)
}

I have tried to replace:

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

with:

fmt.Fprintf("%+v", record)

and receive the following errors:

./test.go:54:21: cannot use "%+v" (type string) as type io.Writer in argument to fmt.Fprintf:
    string does not implement io.Writer (missing Write method)
./test.go:54:21: cannot use record (type Obsidian) as type string in argument to fmt.Fprintf
  • 写回答

2条回答 默认 最新

  • dongluni0568 2017-10-15 23:05
    关注

    Thanks to @MiloChrisstiansen

    fmt.Fprintf(w, "%+v", record)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题