<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're logging it but not returning an appropriate HTTP status code so you'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're trying to do. It's more typical to have routes like </p>
<pre><code>r.Get("/user/:id", GetUser(db))
r.Post("/user", CreateUser(db))
r.Post("/user/:id", ModifyUser(db))
r.Delete("/user/:id", DeleteUser(db))
</code></pre>
<p>So you're using the routes and HTTP methods to specify your resources rather than sending RPC commands. </p>
<p>When the app gets bigger you'll want to put the handlers in a separate package and you'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's going to use a go routine to handle each request already so you don't have to do anything explicitly to take advantage of that. I wouldn'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'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 "defer stmt.Close()" 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大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传