2017-10-15 112 views
0

我对Go /编程一般都很陌生 - 刚刚拿起它,同时还搞乱了创建我自己的加密货币组合网站。在Golang中打印解码的JSON

我正在努力打印到Web服务器输出。如果我使用Printf - 它会打印到控制台,但只要我使用Fprintf打印到Web应用程序,就会出现一些我似乎无法解决的错误。

有人能通过它吗?

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) 
} 

我试图取代:

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

有:

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

,并收到以下错误:

./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 
+0

'fmt.Fprintf(W, “%+ V”,记录)'应该可以解决你的权利了。 –

+0

@MiloChristiansen花了数小时试图弄清楚这一点,你把它排序在5以内!非常感谢 – Thomas

回答

1

由于@MiloChrisstiansen

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

你知道你可以接受你自己的答案吗? – srf

0

你也可以使用

w.Write([]byte(record))