加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

如何使用golang提供json回应?

发布时间:2020-12-16 19:20:52 所属栏目:大数据 来源:网络整理
导读:问题:目前我在func索引中打印出我的回复 像这样fmt.Fprintf(w,string(response))但是,如何在请求中正确地发送json,以便它可能被视图消耗? 包主 import ( "fmt" "github.com/julienschmidt/httprouter" "net/http" "log" "encoding/json")type Payload stru
问题:目前我在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)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读