【问题标题】:Making HTTP responses with JSON [duplicate]使用 JSON 进行 HTTP 响应 [重复]
【发布时间】:2018-03-19 13:12:58
【问题描述】:

我是 Go 新手,我正在尝试构建一个简单的 HTTP 服务器。但是,我遇到了 JSON 响应的一些问题。我编写了以下代码,然后尝试邮递员发送一些 JSON 数据。但是,我的邮递员总是得到一个空的回复,content-typetext/plain; charset=utf-8。然后我在http://www.alexedwards.net/blog/golang-response-snippets#json 中检查了一个样本。我复制并粘贴了示例,它运行良好。但我看不出我的和样品有什么区别。有人可以帮忙吗?

package main

import (
    "encoding/json"
    "net/http"
)

type ResponseCommands struct {
    key   string
    value bool
}

func main() {
    http.HandleFunc("/", handler)
    http.ListenAndServe(":5432", nil)
}

func handler(rw http.ResponseWriter, req *http.Request) {
    responseBody := ResponseCommands{"BackOff", false}

    data, err := json.Marshal(responseBody)
    if err != nil {
        http.Error(rw, err.Error(), http.StatusInternalServerError)
        return
    }
    rw.WriteHeader(200)
    rw.Header().Set("Content-Type", "application/json")
    rw.Write(data)
}

【问题讨论】:

    标签: json go


    【解决方案1】:

    因为 VonC​​trong> 已经回答正确。只是想补充一点,IDEA 可以帮助解决这些“小”问题。 我正在使用 Gogland,它让我知道 json 标签不能应用于小写字段。

    【讨论】:

      【解决方案2】:

      主要区别在于struct中的变量是public的(导出的)

      type Profile struct {
        Name    string
        Hobbies []string
      }
      

      在您的情况下,它们不是(小写)。

      type ResponseCommands struct {
          key   string
          value bool
      }
      

      见“Lowercase JSON key names with JSON Marshal in Go”。

      【讨论】:

      • 感谢您的帮助。这行得通!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-25
      • 2018-11-27
      • 2018-01-16
      • 2021-02-27
      • 1970-01-01
      相关资源
      最近更新 更多