Creating HTTP responses with JSON

I'm new to Go, and I'm trying to practice creating a simple HTTP server. However, I ran into some problems with JSON answers. I wrote the following code, then try the postman to send some JSON data. However, my postman always gets an empty answer, and content-type- text/plain; charset=utf-8. Then I checked the sample at http://www.alexedwards.net/blog/golang-response-snippets#json . I copied and pasted the sample, and it worked well. But I do not see any difference between mine and the sample. Can anyone 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)
}
+5
source share
2 answers

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

type Profile struct {
  Name    string
  Hobbies []string
}

In your case, they are not (lowercase letters).

type ResponseCommands struct {
    key   string
    value bool
}

. " JSON JSON Marshal Go.

+7

VonC . , IDEA "" . Gogland, , json .

0

Source: https://habr.com/ru/post/1687101/


All Articles