json - 如何使用 Go 提供 JSON 响应?

标签 json go

问题:目前我正在 func Index 中打印出我的回复 像这样 fmt.Fprintf(w, string(response)) 但是,如何在请求中正确发送 JSON 以便它可以被 View 使用?

package main

import (
    "fmt"
    "github.com/julienschmidt/httprouter"
    "net/http"
    "log"
    "encoding/json"
)

type Payload struct {
    Stuff Data
}
type Data struct {
    Fruit Fruits
    Veggies Vegetables
}
type Fruits map[string]int
type Vegetables map[string]int


func Index(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
    response, err := getJsonResponse();
    if err != nil {
        panic(err)
    }
    fmt.Fprintf(w, string(response))
}


func main() {
    router := httprouter.New()
    router.GET("/", Index)
    log.Fatal(http.ListenAndServe(":8080", router))
}

func getJsonResponse()([]byte, error) {
    fruits := make(map[string]int)
    fruits["Apples"] = 25
    fruits["Oranges"] = 10

    vegetables := make(map[string]int)
    vegetables["Carrats"] = 10
    vegetables["Beets"] = 0

    d := Data{fruits, vegetables}
    p := Payload{d}

    return json.MarshalIndent(p, "", "  ")
}

最佳答案

您可以设置您的内容类型 header ,以便客户知道期待 json

w.Header().Set("Content-Type", "application/json")

另一种将结构编码为 json 的方法是使用 http.ResponseWriter

构建编码器
// get a payload p := Payload{d}
json.NewEncoder(w).Encode(p)

关于json - 如何使用 Go 提供 JSON 响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31622052/

相关文章:

相当于 scanf %[^\n] 的语言

xml-parsing - Go 中的 DRY struct 标签

java - 将 json 数据传递给 spring-boot 应用程序的 Curl POST 命令不起作用

xml - Go 中的低级 XML 流编写器?

c# - 尝试从 URL 反序列化 .NET 的 JSON,但出现错误

Python 删除 JSON 子字符串

macos - 如何分发 OSX cli/server 应用程序

multithreading - golang线程数误导

javascript - 无法操作 $.post 中的数据

java - HTTP 状态 406。Spring MVC 4.0、jQuery、JSON