使用JSON进行HTTP响应 [英] Making HTTP responses with JSON

查看:550
本文介绍了使用JSON进行HTTP响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am new to Go, and I am trying to practice with building a simple HTTP server. However I met some problems with JSON responses. I wrote following code, then try postman to send some JSON data. However, my postman always gets an empty response and the content-type is text/plain; charset=utf-8. Then I checked a sample in http://www.alexedwards.net/blog/golang-response-snippets#json. I copied and pasted the sample, and it was working well. But I cannot see any difference between mine and the sample. Can someone give some help?

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)
}

推荐答案

主要区别在于结构中的变量是公共的(导出的)

The main difference is that the variable in the struct are public (exported)

type Profile struct {
  Name    string
  Hobbies []string
}

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

In your case, they are not (lowercase).

type ResponseCommands struct {
    key   string
    value bool
}

请参阅"使用JSON元帅在Go中使用小写JSON密钥名称".

这篇关于使用JSON进行HTTP响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆