通过接口对象而不声明结构

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?

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"`,
    ...
}

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

return c.RenderJson(struct{ Error string }{"xyz"})