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 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥15 (关键词-阻抗匹配,HFSS,RFID标签天线)
  • ¥15 机器人轨迹规划相关问题
  • ¥15 word样式右侧翻页键消失