使用http.Request和Restangular在Go中查看JSON POST请求

huangapple go评论87阅读模式
英文:

Seeing JSON POST in Go using http.Request and Restangular

问题

我正在发布以下的 JSON 字符串:

{'foods':[{'vName':'bean','color':'green','size':'small'}, 
          {'vName':'carrot','color':'orange', 'size':'medium'}]}

我正在使用 Restangular 发送到 Go,接收函数是:

func CreateFoods(w http.ResponseWriter, r *http.Request) {
   defer r.Body.Close()
   var food Food //这需要是一个数组或其他吗?
   dec := json.NewDecoder(r.Body)
   dec.Decode(&food)
}

我的 Food 结构体:

type Food struct{

  VName string `json:"vName"`
  Color string `json:"color"`
  Size string `json:"size"`
}

我已经在单个实体的情况下使用了这个例程,但现在我想要发布多个实体,我无法弄清楚如何将这个 JSON 示例映射到多个实体。
另外,我正在尝试“查看”JSON POST,以查看 JSON 字符串,然后如果需要的话,我可以使用该字符串来创建实体。我无法弄清楚如何从 http.Request 中获取 JSON 字符串。

英文:

I'm posting the following json string:

{'foods':[{'vName':'bean','color':'green','size':'small'}, 
           {'vName':'carrot','color':'orange', 'size':'medium'}]}

I'm posting to Go using Restangular, and the receiving func is:

func CreateFoods(w http.ResponseWriter, r *http.Request) {
   defer r.Body.Close()
   var food Food //this needs to be an array or something?
   dec := json.NewDecoder(r.Body)
   dec.Decode(&food)
}

My Food struct:

type Food struct{

  VName string `json:"vName"`
  Color string `json:"color"`
  Size string `json:"size"`
}

I've used this routine for cases where where I post a single entity, but now I want to post multiple entities, and I cannot figure out how to map this json example to multiple entities.
Also, I'm trying to "see" the JSON POST, to see the JSON string, then if I have to, I can work with the string to make the entities. I cannot figure out how to get a hold of the JSON string from http.Request.

答案1

得分: 2

请注意,我将为您提供翻译的内容,但不会执行代码或回答与翻译相关的问题。以下是您要翻译的内容:

添加以下内容:

// 也许您不希望导出,所以可以使用小写的 foods
type Foods struct {
Foods []Food
}

在解码时使用以下代码:

var foods Foods
dec.Decode(&foods)

将响应体作为字符串查看的方法:

bytes, err := ioutil.ReadAll(r.Body)
fmt.Println(string(bytes))

小细节:在最后两行之后,您现在读取了响应体内容。然后,您应该使用 json.Unmarshal 而不是 json.NewDecoder 和 Decode 来解码 JSON。以下是完整的 CreateFoods() 示例,以避免混淆:

bytes, err := ioutil.ReadAll(r.Body)
if err != nil {
fmt.Println("读取请求体时出错")
return
}
fmt.Println(string(bytes))
var foods Foods
json.Unmarshal(bytes, &foods)

希望这样能够正常工作,我没有测试过,请告诉我结果!

英文:

Add this:

// You might use lowercase foods since it is maybe not something you want to export
type Foods struct { 
  Foods []Food
}

When decoding use this:

var foods Foods
dec.Decode(&foods)

To see the body of a response as a string:

bytes, err := ioutil.ReadAll(r.Body)
fmt.Println(string(bytes))

Small detail: After the last two lines you now read the body contents. You should then decode the json not using json.NewDecoder and Decode but json.Unmarshal. Complete example for CreateFoods() to prevent confusion:

bytes, err := ioutil.ReadAll(r.Body)
if err != nil {
  fmt.Println("error reading body")
  return
}
fmt.Println(string(bytes))
var foods Foods
json.Unmarshal(bytes, &foods)

Hope it works, didn't test, let me know!

答案2

得分: 0

如果你有一个io.Reader,处理解码JSON的正确方法是使用json.NewDecoder,使用ioutil.ReadAll然后json.Unmarshal会很慢,并且会创建很多不必要的缓冲区。

要处理像你的JSON示例中的数组,你需要创建一个像这样的结构体:

type Foods struct {
    Foods []Food `json:"foods"`
}

type Food struct {
    VName string `json:"vName"`
    Color string `json:"color"`
    Size  string `json:"size"`
}

func CreateFoods(w http.ResponseWriter, r *http.Request) {
    defer r.Body.Close()
    var foods Foods // 这个需要是一个数组或者其他什么类型?
    dec := json.NewDecoder(r.Body)
    dec.Decode(&foods)
}

然而,如果JSON只是一个数组[{"vName":"bean","color":"green","size":"small"},{"vName":"carrot","color":"orange","size":"medium"}],你可以直接使用:

type Foods []Food

type Food struct {
    VName string `json:"vName"`
    Color string `json:"color"`
    Size  string `json:"size"`
}

func CreateFoods(w http.ResponseWriter, r *http.Request) {
    defer r.Body.Close()
    var foods Foods
    dec := json.NewDecoder(r.Body)
    dec.Decode(&foods)
}
英文:

The proper way to handle decoding json if you have an io.Reader is to use json.NewDecoder, using ioutil.ReadAll then json.Unmarshal is slow and creates a lot of unneeded buffers.

To handle an array like your json example you need to create a struct like this:

type Foods struct {
	Foods []Food `json:"foods"`
}

However if the json is just an array [{'vName':'bean','color':'green','size':'small'} {'vName':'carrot','color':'orange', 'size':'medium'}], you can just use:

type Foods []Food

type Food struct {
	VName string `json:"vName"`
	Color string `json:"color"`
	Size  string `json:"size"`
}

func CreateFoods(w http.ResponseWriter, r *http.Request) {
   defer r.Body.Close()
   var food Foods //this needs to be an array or something?
   dec := json.NewDecoder(r.Body)
   dec.Decode(&foods)
}

huangapple
  • 本文由 发表于 2014年8月25日 02:57:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/25475198.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定