Question: Currently I'm printing out my response in the func Index like this fmt.Fprintf(w, string(response)) however, how can I send JSON properly in the request so that it maybe consumed by a 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, "", "  ")
}

推荐答案

You can set your content-type header so clients know to expect json

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

Another way to marshal a struct to json is to build an encoder using the http.ResponseWriter

// get a payload p := Payload{d}
json.NewEncoder(w).Encode(p)

Json相关问答推荐

如何在Power BI中集成API和JSON数据后将数据转换为表?

Golang返回的JSON顶级字段是可变的.如何在 struct 中使用

如何从一个700MB的json文件中列出PowerShell中的所有密钥?

当由.sh脚本执行时,AWS查询字符串不会提取任何数据

Jolt 变换以展平 json 字符串数组

如何在 terraform 输出中打印一组用户信息

在 CodePipeline 中调用 lambda 时传递用户参数

Powershell v7 文本背景突出显示

Powershell 7.2:ConvertFrom-Json - 日期处理

使用带有逗号的字段名称构建 struct

如何将 XML 转换为 PsCustomObject 以允许最终导出为 JSON?

JSON 模式验证

SyntaxError:Object.parse(本机)AngularJS中的意外标记o

如何获取json格式的KendoGrid显示数据?

如何为名称/值 struct 创建 JSON 模式?

使用 jq 如何用其他名称替换键的名称

Volley JsonObjectRequest Post 参数不再起作用

类型是接口或抽象类,不能实例化

Backbone.js 模型与集合

Javascript对象和JSON对象有什么区别