Can you give me a code review please?

agolangf · · 115 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>Good morning / afternoon / night, i am a beginner looking to learn Go, i made a MariaDB Gin Rest Api to manipulate People data and i am looking for some guidance on my code, can someone give my code a check and tell me where to improve it? i would like code examples too ..</p> <p><a href="https://github.com/clausanoid/MariaDB---Golang---Rest/blob/master/main.go" rel="nofollow">https://github.com/clausanoid/MariaDB---Golang---Rest/blob/master/main.go</a></p> <p>thanks in advance</p> <hr/>**评论:**<br/><br/>luckyleprechaun98: <pre><p>Not bad. Couple things I noticed:</p> <p>When you receive an error in a SQL transaction you&#39;re logging it but not returning an appropriate HTTP status code so you&#39;ll always get 200 even when the operation fails </p> <p>You have your routes set up more like an RPC server rather than a typical REST API. It all depends on what you&#39;re trying to do. It&#39;s more typical to have routes like </p> <pre><code>r.Get(&#34;/user/:id&#34;, GetUser(db)) r.Post(&#34;/user&#34;, CreateUser(db)) r.Post(&#34;/user/:id&#34;, ModifyUser(db)) r.Delete(&#34;/user/:id&#34;, DeleteUser(db)) </code></pre> <p>So you&#39;re using the routes and HTTP methods to specify your resources rather than sending RPC commands. </p> <p>When the app gets bigger you&#39;ll want to put the handlers in a separate package and you&#39;ll likely want to set them up to receive a db connection and return a handler (a closure). This will let you test your handlers and mock the DB connection. </p></pre>Clausanoid: <pre><p>Thanks, i will work on that, do you happen to know how i can optimize it for better concurrency? it is only a learning excercise but i want to start learning the correct way to do things </p></pre>luckyleprechaun98: <pre><p>It&#39;s going to use a go routine to handle each request already so you don&#39;t have to do anything explicitly to take advantage of that. I wouldn&#39;t start doing anything with go routines in your own handlers or using channels until you get a better feel for the language. </p> <p>Also I&#39;d take a look at the <a href="https://github.com/jmoiron/sqlx" rel="nofollow">SQLx library</a>. It can save you a lot of boilerplate in your SQL queries. </p></pre>alasijia: <pre><p>all &#34;defer stmt.Close()&#34; should be placed before stmt.Exec.</p> <p>On the other hand, the statements should be global variables to get better performance.</p></pre>

入群交流(和以上内容无关):Go中文网 QQ 交流群:798786647 或加微信入微信群:274768166 备注:入群;关注公众号:Go语言中文网

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