一尘不染

如何使用 Go 提供 JSON 响应?

go

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

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

阅读 149

收藏
2021-11-18

共1个答案

一尘不染

您可以设置内容类型标头,以便客户知道期望 json

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

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

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