Go newbie: how to organize code

polaris · · 445 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>Hello, I&#39;m new to Go, and i have some doubts about how to organize code. I don&#39;t know if I understand packages correctly. Let&#39;s asume that I&#39;m making a rest api, and I wanna organize my code by functionality. Will be this organization correct?</p> <pre><code>main.go users/users.go </code></pre> <p>users.go will contain all user code: types, handler functions... And in main.go I will import this package as &#34;[fullpath]/users&#34;</p> <p>Is this correct? If not, what will be the correct way of doing this?</p> <p>Thanks in advance.</p> <hr/>**评论:**<br/><br/>nstratos: <pre><p>Hello,</p> <p>This is a common question in the Go community. Please <a href="https://www.reddit.com/r/golang/comments/56wk4v/structuring_go_api/d8n4axl/" rel="nofollow">read my previous answer</a> on a similar topic.</p> <blockquote> <p>Will be this organization correct?</p> <pre><code>main.go users/users.go </code></pre> </blockquote> <p>I believe that instead of a generic package name <code>users</code> which would lead to <code>users.User</code>, it would be better if you used a package name that is relevant to your application or domain. So for example if your application is called <code>dpe</code> then you would have <code>dpe.User</code>.</p> <p>Using a single <code>main.go</code> on the root of your project is a common way to start a project. If later you decide that you need more commands, you might want to do something like this:</p> <pre><code>cmd/dpetool/main.go cmd/dpeserver/main.go dpe/users.go </code></pre> <p>A good project to draw inspiration about code organization is <a href="https://github.com/upspin/upspin" rel="nofollow">Upspin</a>.</p></pre>dp404e: <pre><p>Thanks a lot! Sorry for asking something already answered.</p> <p>I&#39;ll check the articles in your previous answer.</p></pre>bestfoodnearme: <pre><p>for a web server type <a href="https://bestfoodnearme.com" rel="nofollow">project</a> I use this structure below. I use the Makefile to build the binaries under main, to run all tests, to compile sass to css and minify it.</p> <pre><code>/ Makefile /sass/ /tmpl/ index.tmpl /css/ /js/ /images/ /main/ server.go microservice1.go microservice1.go /lib /database/ /config/ /controllers/ /models/ /utility/ /vendor/ </code></pre></pre>

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

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