如何使用 Go 提供 JSON 响应?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31622052/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 17:59:10  来源:igfitidea点击:

How to serve up a JSON response using Go?

jsongo

提问by Matthew Harwood

Question:Currently I'm printing out my response in the func Indexlike this fmt.Fprintf(w, string(response))however, how can I send JSON properly in the request so that it maybe consumed by a view?

问题:目前我正在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, "", "  ")
}

回答by dm03514

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

您可以设置内容类型标头,以便客户知道期望 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

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

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

回答by k3mist

Other users commenting that the Content-Typeis plain/textwhen encoding. You have to set the Content-Typefirst w.Header().Set, then the HTTP response code w.WriteHeader.

其他用户评论说Content-Typeplain/text编码时。你必须设置的Content-Type第一w.Header().Set,那么HTTP响应代码w.WriteHeader

If you call w.WriteHeaderfirst then call w.Header().Setafter you will get plain/text.

如果你w.WriteHeader先打电话w.Header().Set,然后再打电话,你会得到plain/text

An example handler might look like this;

示例处理程序可能如下所示;

func SomeHandler(w http.ResponseWriter, r *http.Request) {
    data := SomeStruct{}
    w.Header().Set("Content-Type", "application/json")
    w.WriteHeader(http.StatusCreated)
    json.NewEncoder(w).Encode(data)
}

回答by poorva

You can do something like this in you getJsonResponsefunction -

你可以在你的getJsonResponse函数中做这样的事情-

jData, err := json.Marshal(Data)
if err != nil {
    // handle error
}
w.Header().Set("Content-Type", "application/json")
w.Write(jData)

回答by Aleks Tkachenko

In gobuffalo.io framework I got it to work like this:

在 gobuffalo.io 框架中,我让它像这样工作:

// say we are in some resource Show action
// some code is omitted
user := &models.User{}
if c.Request().Header.Get("Content-type") == "application/json" {
    return c.Render(200, r.JSON(user))
} else {
    // Make user available inside the html template
    c.Set("user", user)
    return c.Render(200, r.HTML("users/show.html"))
}

and then when I want to get JSON response for that resource I have to set "Content-type" to "application/json" and it works.

然后当我想获得该资源的 JSON 响应时,我必须将“内容类型”设置为“应用程序/json”并且它可以工作。

I think Rails has more convenient way to handle multiple response types, I didn't see the same in gobuffalo so far.

我认为 Rails 有更方便的方法来处理多种响应类型,到目前为止我在 gobuffalo 中没有看到相同的方法。

回答by Aleks Tkachenko

You may use this package renderer, I have written to solve this kind of problem, it's a wrapper to serve JSON, JSONP, XML, HTML etc.

你可以使用这个包渲染器,我写来解决这种问题,它是一个包装器来提供 JSON、JSONP、XML、HTML 等。