doubi4340 2017-05-01 17:34
浏览 17
已采纳

在GO中毒化套件/功能

TLDR: Is there a way in golang (even if it is a bit non-standard), to "poison" a function or import of a certain package altogether.

The longer version: I am writing a thrift service, which all public facing functions return results, or an error of a certain type, declared in the thrift file. The code generator generates code for the interface like this:

publicFacingFunc(...) (returnType, error)

This would be great, until someone I am working with decides to check for another condition, and when that condition is not met does something like this:

if conditionIsNotMet {
    return nil, errors.New(...)
}

The code compiles, but when the error arises, the received message is undocumented random string. So in these files, I want to prevent usage of "errors" and "fmt" packages.

And yes, I tried, and still have I a blaring warning at the top of the file, but nobody seems to read.

BTW, the public errors all have a respective "constructor", which is external to these files, and only those should be used, in my case.

  • 写回答

2条回答 默认 最新

  • douguazhi5966 2017-05-01 17:38
    关注

    If you're only concerned with a packages use within a file, you could import it under a silly name, like 'NEVER'... and people could use it, but they'd get the idea I think.

     import (
          NEVER "fmt"
     )
    

    OR, if you want to be less silly, you could use the _ underscore, https://golang.org/doc/effective_go.html#blank_import

    import (
        _ "fmt"
    )
    

    which will load the import, but only it's side effects (that is, not for explicit use.


    To stop the input of all errors not of a certain type, you could use reflect in order to stop the undesirable types with type assertion, https://golang.org/ref/spec#Type_assertions

    v, ok = x.(T)
    

    So if an err comes up in the public facing function, that you don't want passed through, check what kind of error it is,

     specialError, ok := err.(mypackage.ErrorType)
        if !ok {
            // don't send this error on
        } 
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥30 自适应 LMS 算法实现 FIR 最佳维纳滤波器matlab方案
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥15 Python3.5 相关代码写作
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像