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:
guglicap:
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
Module
s, callRun(mychannel)
on each in a goroutine, and handle incoming events onmychannel
.
xuoe: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.
guglicap:You could implement the
json.Unmarshaler
interface on theConfig
struct and usejson.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 tojson.Unmarshal(data, &conf)
would suffice there.EDIT 2: here's, what I hope to be, an improved version.
Thanks a lot, that should do.
