gpt4 book ai didi

json - 在 Golang 中打印解码后的 JSON

转载 作者:IT王子 更新时间:2023-10-29 02:02:39 26 4
gpt4 key购买 nike

总的来说,我对 Go/编程还很陌生 - 刚刚开始学习它,同时忙于创建我自己的加密货币投资组合网站。

我正在努力打印到网络服务器输出。如果我使用 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

最佳答案

感谢@MiloChristiansen

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

关于json - 在 Golang 中打印解码后的 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46760795/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com