Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making HTTP responses with JSON [duplicate]

Tags:

json

go

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)
}
like image 710
Lehtia Avatar asked Oct 08 '17 04:10

Lehtia


People also ask

Can JSON have duplicate values?

We can have duplicate keys in a JSON object, and it would still be valid. The validity of duplicate keys in JSON is an exception and not a rule, so this becomes a problem when it comes to actual implementations.

Can JSON contain duplicate keys?

JSON with duplicate key entries have to be handled either by ignoring the duplicate entries or by throwing an exception. Until Mule Runtimes 3.8. 6/3.9. 0, JSON Schema Validator handles them by retaining the last duplicate entry and not throwing an exception.

How does JSON handle duplicate keys?

Parse the string using wither regex or tokens, add each key-value pair to a hashmap, and in the end recreate your JSON document with the duplicates removed. In this case though I would only remove key-value pairs that are exactly the same.

What is the HTTP status code for duplicate record?

409 Conflict - Client attempting to create a duplicate record, which is not allowed. 410 Gone - The requested resource has been deleted.


1 Answers

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

like image 149
VonC Avatar answered Sep 24 '22 03:09

VonC