douzhenyu6533 2019-03-03 05:53
浏览 1427
已采纳

解决Go中循环依赖的最佳实践

I have a Go project that contains both of these packages:

  • logging
    Imports config, because I want to send the current configuration to my error reporting system
  • config
    Imports logging, because I want to log if the program is unable to open the config files

What is the best practice for resolving this dependency error?

  • 写回答

1条回答 默认 最新

  • duangelin7513 2019-03-03 06:24
    关注

    In what format are you sending the configuration to the error reporting system? Maybe pass that to logging? Say, if it's json, then marshal the config before giving it to logging and then give logging the []byte result only.

    But in general, if two packages depend on each other directly what you can do is have one of them declare an interface that matches the other one's behaviour and then have a separate package pass the concrete instance as the interface.

    For example:

    /myapp/config

    import "myapp/logging"
    
    type Config struct {
         // ...
    }
    
    func NewConfig() *Config {
        // ...
        if err != nil {
            logging.LogError(err)
        }
    }
    

    /myapp/logging

    import "myapp/config"
    
    func LogConfig(c *config.Config) {
        // ...
    }
    
    func LogError(err error) {
        // ...
    }
    

    So in this case you could declare an interface in the config package that matches the behaviour it needs from logging.

    /myapp/config

    type Logging interface {
        LogError(error)
    }
    
    var logging Logging
    
    func SetLogging(l Logging) {
        logging = l
    }
    
    type Config struct {
         // ...
    }
    
    func NewConfig() *Config {
        // ...
        if err != nil {
            logging.LogError(err)
        }
    }
    

    And then have a type in the logging package implement that interface by simply delegating to the original functions.

    /myapp/logging

    import "myapp/config"
    
    func LogConfig(c *config.Config) {
        // ...
    }
    
    func LogError(err error) {
        // ...
    }
    
    type Logging struct{}
    
    func (Logging) LogError(err error) {
        LogError(err)
    }
    

    And lastly have a third package make it all work together.

    /myapp

    import "myapp/config"
    import "myapp/logging"
    
    func init() {
        config.SetLogging(logging.Logging{})
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题