I have a struct like this:
type User struct {
Login string `json:",string"`
PasswordNonce Nonce `json:",string"`
PasswordHash HashValue `json:",string"`
CreatedOn time.Time `json:",string"`
Email string `json:",string"`
PhoneNumber string `json:",string"`
UserId Id `json:",string"`
}
The code that generates the JSON and sends it is the following:
func AddUserHandler(w http.ResponseWriter, r *http.Request) {
var userRecord model.User
encoder := json.NewEncoder(w)
err = encoder.Encode(userRecord)
if err != nil {
panic(err)
}
}
When I encode it with the Golang built in JSON encoder, the field names appear without quotes, which prevents the JSON.parse function in node.js from reading the content.
Does anyone know a solution to that?
Thanks!
It was my mistake. The problem was in the Javascript code.
I am using the node.js request package, and it seems to parse JSON responses by default. In the following code, response.body is already a map containing the parsed contents of the JSON string:
var request = require('request');
var options = {
uri: 'http://localhost:3000/AddUser',
method: 'POST',
json: {}
};
request(options, function(error, response, body) {
console.log(error)
console.log(response.body)
console.log(response.body["UserId"])
data = response.body
// data = JSON.parse(response.body) gives an error...
});
package main
import (
"encoding/json"
"math/rand"
"net/http"
"time"
)
type Nonce [32]byte
type HashValue [32]byte
type Id [32]byte
func MakeNonce() Nonce {
return makeByte32()
}
func MakeHashValue() HashValue {
return makeByte32()
}
func MakeId() Id {
return makeByte32()
}
func makeByte32() [32]byte {
bytes := [32]byte{}
rand.Seed(time.Now().Unix())
for i, _ := range bytes {
bytes[i] = byte(48 + (rand.Float64() * 10))
}
return bytes
}
type User struct {
Login string
PasswordNonce Nonce
PasswordHash HashValue
CreatedOn time.Time
Email string
PhoneNumber string
UserId Id
}
type myHandler struct {
userRecord User
}
func (mh myHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
encoder := json.NewEncoder(w)
err := encoder.Encode(mh.userRecord)
if err != nil {
panic(err)
}
}
func main() {
user := User{
"test",
MakeNonce(),
MakeHashValue(),
time.Now(),
"[email protected]",
"5195555555",
MakeId(),
}
h := myHandler{user}
http.ListenAndServe("localhost:4000", h)
}