4

I have a very simple http resonse in my server where i json encode a struct. But its sending a blank of just {}

I don't know if i am doing it wrong but i get no errors. This is my json encode:

    // Set uuid as string to user struct
    user := User{uuid: uuid.String()}
    fmt.Println(user) // check it has the uuid

    responseWriter.Header().Set("Content-Type", "application/json")
    responseWriter.WriteHeader(http.StatusCreated)

    json.NewEncoder(responseWriter).Encode(user)

On the recieving end the data has:

Content-Type application/json
Content-Length 3
STATUS HTTP/1.1 201 Created
{}

Why does it not give me the uuid data? Am i doing something wrong with my encoding?

Sir
  • 8,135
  • 17
  • 83
  • 146
  • 8
    Export the field names. See possible duplicate https://stackoverflow.com/questions/26327391/go-json-marshalstruct-returns. – Charlie Tumahai Nov 01 '17 at 04:17
  • Ill try it out see if it works. – Sir Nov 01 '17 at 05:00
  • 3
    Possible duplicate of [Go json.Marshal(struct) returns "{}"](https://stackoverflow.com/questions/26327391/go-json-marshalstruct-returns) – tgogos Nov 01 '17 at 09:10
  • @tgogos that wasn't the solution in this case. See the answer below, it was a mistake in my syntax. – Sir Nov 01 '17 at 23:29

1 Answers1

10

Export the field name by making the first character of the identifier's name a Unicode upper case letter (Unicode class "Lu").

Try this:

package main

import (
    "encoding/json"
    "fmt"
    "log"
    "net/http"
)

type User struct {
    Uuid string
}

func handler(responseWriter http.ResponseWriter, r *http.Request) {
    user := User{Uuid: "id1234657..."} // Set uuid as string to user struct
    fmt.Println(user)                 // check it has the uuid
    responseWriter.Header().Set("Content-Type", "application/json")
    responseWriter.WriteHeader(http.StatusCreated)
    json.NewEncoder(responseWriter).Encode(user)
}

func main() {
    http.HandleFunc("/", handler)            // set router
    err := http.ListenAndServe(":9090", nil) // set listen port
    if err != nil {
        log.Fatal("ListenAndServe: ", err)
    }
}

output(http://localhost:9090/):

{"Uuid":"id1234657..."}
wasmup
  • 14,541
  • 6
  • 42
  • 58