8

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)
}
Dave C
  • 7,729
  • 4
  • 49
  • 65
Lehtia
  • 159
  • 1
  • 3
  • 12

2 Answers2

9

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

VonC
  • 1,262,500
  • 529
  • 4,410
  • 5,250
0

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.

Farrukh Okhunov
  • 441
  • 1
  • 4
  • 6