Hi, I'd need some help with a design problem.

xuanbao · 2017-03-05 21:00:08 · 603 次点击    
这是一个分享于 2017-03-05 21:00:08 的资源,其中的信息可能已经有所发展或是发生改变。

Hello guys,
I'm writing a program to generate input for lemonbar, using json files as config.
My idea is that I'll have different types of modules (or blocks) like username, date, clock ecc...
How I'm handling this right now is that I have only one struct called Module which has a Handler variable that is assigned to a different functions based on what the json file says. I don't really like this solution, because I can't keep things like per-module options separated, but I would love to hear your opinion on that. I think a nice way to do it would be having separate structs for each module type, but I couldn't figure out how to implement it.
You can find the code here.
Thanks.


评论:

beknowly:

Module can be an interface if you want modules that are used the same way but have implementation specific state.

type Module interface {
      Run(msg chan bool)
      // whatever other required methods
}
type NetModule struct {
     // whatever state you need in a NetModule
}
func (n NetModule) Run(msg chan bool) {
    // do whatever this module does
    for {
        time.Sleep(1 * time.Second)
        msg <- true
    }
}

Then you can instantiate say, a slice of Modules, call Run(mychannel) on each in a goroutine, and handle incoming events on mychannel.

guglicap:

Thanks for the reply.
That would be the solution I thought of initially, but I couldn't figure out how to implement, mostly because of JSON.
Most of these modules have the same properties, say
{ "Handler":"net", "Refresh":"3s", ... "Options":{ What differs from module to module is this part, as I'll have say NetInterface as an options for this module but Format as an option for the date one. }
Thus, how can I know what to unmarshal it into? I don't think I can unmarshal it into []Module, since Module is an interface.

EDIT: By the way, here's an example config file, since I'm on mobile and the example I typed is probably not well formatted.

xuoe:

You could implement the json.Unmarshaler interface on the Config struct and use json.RawMessage for module-specific options. That might work. Have a look here, where I took some of your code and applied those ideas (including, to some extent, what /u/beknowly suggested).

EDIT 1: in the code snippet, creating a json.Decoder is not necessary (line 51), as a call to json.Unmarshal(data, &conf) would suffice there.

EDIT 2: here's, what I hope to be, an improved version.

guglicap:

Thanks a lot, that should do.


入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

603 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传