如何使用golang提供json回应?

前端之家收集整理的这篇文章主要介绍了如何使用golang提供json回应?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
问题:目前我在func索引中打印出我的回复
像这样fmt.Fprintf(w,string(response))但是,如何在请求中正确地发送json,以便它可能被视图消耗?

包主

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,"","  ")
}
您可以设置您的内容类型标题,以便客户端知道期望json

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

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

// get a payload p := Payload{d}
json.NewEncoder(w).Encode(p)
原文链接:https://www.f2er.com/go/187006.html

猜你在找的Go相关文章