大佬教程收集整理的这篇文章主要介绍了如何使用 Go 提供 JSON 响应?,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
您可以设置内容类型标头,以便客户知道期望 Json
w.header().Set("Content-Type", "application/Json")
将结构编组为 Json 的另一种方法是使用 http.ResponseWriter
// get a payload p := Payload{D}
Json.NewEncoder(w).Encode(p)
问题:目前我正在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,""," ")
}
以上是大佬教程为你收集整理的如何使用 Go 提供 JSON 响应?全部内容,希望文章能够帮你解决如何使用 Go 提供 JSON 响应?所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。