0

How can I pass an Interface{} object without declaring a Struct? for example when I'm using the Revel framework I want to return an error on a specific case.

  1. The following example is not working, I tried various conventions nothing worked, whats the right approach?

    return c.RenderJson(interface{"error":"xyz"})

  2. Whats the right approach to return an error to the Client if i'm building a Server with the Revel framework?

Dino
  • 65
  • 1
  • 4

2 Answers2

4

You don't have to declare a named struct type prior, you could simply use:

return c.RenderJson(struct{ Error string }{"xyz"})
icza
  • 389,944
  • 63
  • 907
  • 827
4

For 1. Try the following:

return c.RenderJson(map[string]string{"error": "xyz"})

RenderJson takes an interface, which means you can pass it anything. You don't need to explicitly cast to an interface, though that would be done like

interface{}(map[string]string{"error": "xyz"})

For 2. I am not certain, but I tend to have a helper function that takes the error string (or error type) and a status code and does the handling for me.

return HandleError(c, "xyz is not valid", 400)

And then HandleError just creates and writes the error.

If you are going to be handling errors in general, I don't know why you wouldn't make an error type though,

type RequestError struct {
    Error string `json:"error_message"`,
    StatusCode int `json:"status_code"`,
    ...
}
sberry
  • 128,281
  • 18
  • 138
  • 165
  • That's exactly what I was looking for, thanks. could you redirect me to a source that's saying what exactly does the `json:"error_message"` mean in the struct? I am a newbie to Golang so it's the first time i'm seeing it – Dino Mar 02 '15 at 20:33
  • Have a look in here: http://golang.org/pkg/encoding/json/#Marshal. They are called struct tags. This is how they are used via reflect: http://golang.org/pkg/reflect/#StructTag. And here is a bit of explanation in general: https://golang.org/ref/spec#Struct_types – sberry Mar 02 '15 at 20:59