duanqing2209 2017-10-08 04:49
浏览 124
已采纳

使用JSON进行HTTP响应[重复]

This question already has an answer here:

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)
}
</div>
  • 写回答

2条回答 默认 最新

  • dongmeng2509 2017-10-08 04:51
    关注

    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
    }
    

    See "Lowercase JSON key names with JSON Marshal in Go".

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 matlab求解平差
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊
  • ¥15 安装svn网络有问题怎么办
  • ¥15 vue2登录调用后端接口如何实现