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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?