doudong2149 2015-11-25 12:03
浏览 68
已采纳

Go-将泛型结构传递给函数

Considering the following code, which is responding to GET '/venues/:id':

func venueShow(w http.ResponseWriter, req *http.Request) {

  // get ID from params
  vars := mux.Vars(req)
  id := vars["id"]

  // initialise new struct
  var venue Venue

  // select by id and scan into struct
  db.First(&venue, id).Scan(&venue)

  // turn it to json
  response := structToJSON(&venue)

  // write headers and provide response
  w.Header().Set("Content-Type", "application/json")
  w.Write(response)
}

and:

func structToJSON (s interface{}) (response []byte) {
  // turn it into pretty-ish json
  response, err := json.MarshalIndent(&s, "", "  ")
  if err != nil {
   return []byte("Venue does not exist")
  }
  // return the json as the reponse
  return response
}

My structToJSON function is taking an empty interface as the argument, because I want to pass various different structs to the function and have them spewed out as JSON.

However, it doesn't strike me as very safe. If anything satisfies an empty interface, I could pass whatever I wanted into that function, and all sorts of errors might happen when json.Marshal tries to do it's business. This (I suppose) would be caught by the compiler rather than at runtime, but is there a safer way?

I could duplicate the structToJSON method for each different type of Struct/Model that I pass to it, but that's not very DRY.

Thanks

  • 写回答

1条回答 默认 最新

  • dongwan0574 2015-11-25 12:24
    关注

    The Marshal function also receives its parameters as interface{} therefore there's no way to detect if you are passing something invalid at compile time, it's all caught at runtime.

    One thing you can do to check if an invalid type was passed to Marshal is to check the error type, Marshal returns an UnsupportedTypeError when you try to Marshal an invalid type (like chan or func) so you can check for that error when Marshaling.

    So you could try something like that:

    if err != nil {
        _, ok := err.(*json.UnsupportedTypeError)
        if ok {
            return []byte("Tried to Marshal Invalid Type")
        } else {
            return []byte("Venue does not exist")
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 PointNet++的onnx模型只能使用一次
  • ¥20 西南科技大学数字信号处理
  • ¥15 有两个非常“自以为是”烦人的问题急期待大家解决!
  • ¥30 STM32 INMP441无法读取数据
  • ¥15 R语言绘制密度图,一个密度曲线内fill不同颜色如何实现
  • ¥100 求汇川机器人IRCB300控制器和示教器同版本升级固件文件升级包
  • ¥15 用visualstudio2022创建vue项目后无法启动
  • ¥15 x趋于0时tanx-sinx极限可以拆开算吗
  • ¥500 把面具戴到人脸上,请大家贡献智慧,别用大模型回答,大模型的答案没啥用
  • ¥15 任意一个散点图自己下载其js脚本文件并做成独立的案例页面,不要作在线的,要离线状态。