json.NewEncoder returns extra line and SyntaxError: Unexpected end of input()

323 views
Skip to first unread message

Ron Dyck

unread,
Feb 16, 2016, 9:10:04 PM2/16/16
to golang-nuts
I created a service with golang that returns a small json object upon successful login. However the response returns what appears to be an extra line that cause errors when parsing with a javascript client. Here's the returned object as I see it in Chrome network response:

{"token":"abc","id":"zzz","email":"me"}


All is good except for the extra line after the json object. Here's my go code from my handler:

type profile struct {
  Token    string `json:"token"`
  UserID   string `json:"id"`
  Username string `json:"email"`
}

func Login(e *Env, w http.ResponseWriter, r *http.Request) error {

  ...

  p := &profile{
    Token:    "abc",
    Username: "me",
    UserID:   "zzz",
   }

  json.NewEncoder(w).Encode(p)
  return nil
}

I've mocked a similar response without the extra line and the client works fine, the extra whitespace is invalid json. So if I could somehow 'trim' the output things would be good. I'm at a loss for why go would return json this way or am I doing something wrong?

Any help would really be appreciated.

ron

Caleb Spare

unread,
Feb 16, 2016, 9:15:33 PM2/16/16
to Ron Dyck, golang-nuts
​json.Encoder is intended for writing multiple newline-delimited JSON objects to a stream. Encode is documented to write a newline after the object:


If you just want to write a single json object, you could json.Marshal(p) and then w.Write the result.​

Also, I would recommend checking errors (in your code, an encoding or writing error will be silently ignored).

--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Ron Dyck

unread,
Feb 17, 2016, 8:14:03 AM2/17/16
to golang-nuts, ro...@webbtech.net
Turns out it wasn't the extra whitespace after the json, I had the 'mode' set to 'no-cors' (I'm using the new 'fetch' method in js) and that was causing the error. Researching the error led me to believe it was caused by malformed json, not a problem in this case. After setting up my pre-flight and other headers I removed the no-cors and all is working.
Thanks for your help.

ron
Reply all
Reply to author
Forward
0 new messages