duanqing2209
2017-10-08 04:49
浏览 90

使用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>

图片转代码服务由CSDN问答提供 功能建议

此问题已经存在 在这里有答案:

  • json。解组返回空白结构 1个答案 < / li>

    我是Go的新手,我正在尝试构建一个简单的HTTP服务器。 但是我在JSON响应中遇到了一些问题。 我编写了以下代码,然后尝试邮递员发送一些JSON数据。 但是,我的邮递员总是得到空响应,并且 content-type text / plain; 字符集= UTF-8 。 然后,我在 http://www.alexedwards.net/blog/中检查了一个示例 golang-响应片段#JSON 。 我复制并粘贴了示例,它运行良好。 但是我看不到我和样本之间的任何区别。 有人可以帮忙吗?

     程序包main 
     
    import(
    “ encoding / json” 
    “ net / http” 
    )
     
    type ResponseCommands结构 {
    键串
    值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)
    如果出现错误!=  nil {
     http.Error(rw,err.Error(),http.StatusInternalServerError)
     return 
    } 
     rw.WriteHeader(200)
     rw.Header()。Set(“ Content-Type”,  “ application / json”)
     rw.Write(data)
    } 
       
     
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

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".

    点赞 打赏 评论
  • doudiecai1572 2017-10-09 07:27

    As VonC already answered correct. Just want to add that IDEA can help with such 'small' problems. I'm using Gogland and it let me know that json tag cannot be applied to lowercase field.

    点赞 打赏 评论

相关推荐 更多相似问题