Restful API + database

blov · · 1070 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>Hello all, I have been trying to use &#34;<a href="https://github.com/mattn/go-sqlite3">https://github.com/mattn/go-sqlite3</a>&#34; to connect to database. I seem to stuck in between. How do i pass opened db object to each HandleFunc or should I open within every HandleFunc on each call?</p> <hr/>**评论:**<br/><br/>sjustinas: <pre><p>You probably shouldn&#39;t open a database connection on each request, as <code>database/sql</code> will pool connections for you automatically.</p> <p>You have severals ways to achieve what you need. The ones to come to my mind right now is either having a global DB object, or passing the DB handle using a closure:</p> <pre><code>func handlerWithDb(db *sql.DB) http.Handler { return http.HandlerFunc(func(...) { // use `db` }) } </code></pre></pre>media_guru: <pre><p>I&#39;ve used a global in the past for this, but I&#39;ve seen some contention among some gophers about using globals (whether they&#39;re good or bad).</p> <p>Either way, OP -- definitely let database/sql manage the connection for you. </p></pre>param_at_ma: <pre><p>Since first option is quite easy, I will try out with that first. Later while refactoring i would go with second option (It might take some time understand). Anyway Thanks a ton :)</p></pre>3Dayo: <pre><p>Permit me to suggest the following article: <a href="http://www.alexedwards.net/blog/organising-database-access">Organising Database Access</a></p></pre>param_at_ma: <pre><p>Indeed very good article, since I am new to golang, this gave so much knowledge.It answered my next question also. &#34;How to make database and model as separate package&#34;. Thank you very much for the right direction :)</p></pre>jeffmetal: <pre><p>I just copied the way the techempower benchmark code did it, which is using a global pool. <a href="https://github.com/TechEmpower/FrameworkBenchmarks/blob/master/frameworks/Go/go/src/hello/hello.go" rel="nofollow">https://github.com/TechEmpower/FrameworkBenchmarks/blob/master/frameworks/Go/go/src/hello/hello.go</a></p></pre>param_at_ma: <pre><p>I will follow the code. Thank you very much :)</p></pre>

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

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