douzhanshen0657 2015-03-02 20:14
浏览 21
已采纳

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

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?

  • 写回答

2条回答 默认 最新

  • duanhe1976 2015-03-02 20:22
    关注

    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"`,
        ...
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 在获取boss直聘的聊天的时候只能获取到前40条聊天数据
  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开
  • ¥15 marlin编译错误,如何解决?
  • ¥15 有偿四位数,节约算法和扫描算法
  • ¥15 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集