我对Go /编程一般都很陌生 - 刚刚搞砸了创建我自己的加密货币组合网站。
我正在努力打印到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 :(得分:2)
感谢@MiloChrisstiansen
fmt.Fprintf(w, "%+v", record)
答案 1 :(得分:0)
您也可以使用
w.Write([]byte(record))