Question: design issue and idiomatic go

polaris · · 441 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>I currently have a client for a system that can do:</p> <ul> <li>fetch (a set of messages)</li> <li>ack (a single message with ok or error)</li> <li>ackall (all messages, only ok at this time)</li> </ul> <p>On top of this i will build a listener, a background process that will fetch and ack on the background, doing work in a caller supplied function that handles the payload. -&gt; Listen( handlerFunc ..) Since this is a background process there is also a Stop() method to shutdown in a clean manner.</p> <p>I can add these methods to the existing client or create a new Listener struct that embeds a client.</p> <p>What is the idiomatic way? I suppose providing a simple Listen function that works is preferred over having different types of Listeners over time. That feels more Java-like for me. Some other thoughs i considered:</p> <p>Suppose this is the first listener called &#39;SimpleListener&#39;. Then i could MultiWorkerMultiFetcherListener with a smart way to error on the single errors and multi-ack the rest. But the optimizations and changes i would do there are just as valid for SimpleListener.</p> <p>Then i could imagine BatchListener which would only acknowlegde after processing the whole set of messages because it would use some single database transaction for efficiency purposes in the client.</p> <p>Opinions welcome!</p> <hr/>**评论:**<br/><br/>DeedleFake: <pre><p>Without seeing more of the code it&#39;s kind of hard to give a good answer. However, as a general rule, if you find yourself tempted to make a MultiWorkerMultiFetcherListener then you&#39;re probably doing something wrong. Without knowing exactly what you&#39;re doing, my suggestion would be to try to structure the code like the <code>net/http</code> package&#39;s handler system. That system lends itself towards composition; you can build handlers to do what you want by breaking them down into small parts and chaining them. For example, let&#39;s say you want to serve files, cache them, and also handle errors nicely. You could do something like this:</p> <pre><code>type cacheFS struct { FS http.FileSystem } func CacheFS(fs http.FileSystem) http.FileSystem { return &amp;cacheFS{FS: fs} } func (fs *cacheFS)Open(file string) (http.File, error) { // Cache stuff. } func ErrorHandler(h http.Handler) http.Handler { return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { // Handle errors. }) } func main() { http.Handle(&#34;/static/&#34;, ErrorHandler(http.FileServer(CacheFS(http.Dir(&#34;static&#34;))))) } </code></pre></pre>

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

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