Noob gopher here, please review my code

polaris · · 469 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>I&#39;ve written a simple REST API deployed on AWS elasticbeanstalk that talks to an AWS RDS. </p> <pre><code>package main import ( &#34;database/sql&#34; &#34;encoding/json&#34; &#34;fmt&#34; &#34;log&#34; &#34;net/http&#34; &#34;os&#34; _ &#34;github.com/go-sql-driver/mysql&#34; &#34;github.com/gorilla/mux&#34; ) type Message struct { ID int `json:&#34;id&#34;` Body string `json:&#34;message_body&#34;` Recipient string `json:&#34;message_recipient&#34;` } var ( dataSourceName = fmt.Sprintf(&#34;%s:%s@tcp(%s:%s)/%s&#34;, os.Getenv(&#34;RDS_USERNAME&#34;), os.Getenv(&#34;RDS_PASSWORD&#34;), os.Getenv(&#34;RDS_HOSTNAME&#34;), os.Getenv(&#34;RDS_PORT&#34;), &#34;test_msg&#34;) getAllMessagesQuery = &#34;SELECT id, message_body, message_recipient FROM message_tbl&#34; getMessageByIDQuery = &#34;SELECT id, message_body, message_recipient FROM message_tbl WHERE id=?&#34; postMessageQuery = &#34;INSERT INTO message_tbl(message_body, message_recipient) VALUES(?,?)&#34; db *sql.DB ) func main() { db, _ = sql.Open(&#34;mysql&#34;, dataSourceName) defer db.Close() router := mux.NewRouter() router.StrictSlash(true) router.HandleFunc(&#34;/message&#34;, GetAllMessages).Methods(&#34;GET&#34;) router.HandleFunc(&#34;/message/{id}&#34;, GetMessageByID).Methods(&#34;GET&#34;) router.HandleFunc(&#34;/message&#34;, PostMessage).Methods(&#34;POST&#34;) log.Fatal(http.ListenAndServe(&#34;:5000&#34;, router)) } func PostMessage(w http.ResponseWriter, req *http.Request) { decoder := json.NewDecoder(req.Body) var m Message err := decoder.Decode(&amp;m) if err != nil { panic(err) } w.Header().Set(&#34;Content-Type&#34;, &#34;application/json&#34;) if m.Body == &#34;&#34; || m.Recipient == &#34;&#34; { invalid := struct { ErrorMessage string `json:&#34;error_message&#34;` }{ &#34;Invalid parameters&#34;, } w.WriteHeader(http.StatusBadRequest) json.NewEncoder(w).Encode(invalid) return } res, _ := db.Exec(postMessageQuery, m.Body, m.Recipient) lastID, _ := res.LastInsertId() returnID := struct { LastID int64 `json:&#34;message_id&#34;` }{ lastID, } w.WriteHeader(http.StatusCreated) json.NewEncoder(w).Encode(returnID) } func GetAllMessages(w http.ResponseWriter, req *http.Request) { var messages []Message rows, _ := db.Query(getAllMessagesQuery) defer rows.Close() for rows.Next() { var m Message rows.Scan(&amp;m.ID, &amp;m.Body, &amp;m.Recipient) messages = append(messages, m) } w.Header().Set(&#34;Content-Type&#34;, &#34;application/json&#34;) json.NewEncoder(w).Encode(messages) } func GetMessageByID(w http.ResponseWriter, req *http.Request) { params := mux.Vars(req) messageID := params[&#34;id&#34;] w.Header().Set(&#34;Content-Type&#34;, &#34;application/json&#34;) var m Message err := db.QueryRow(getMessageByIDQuery, messageID).Scan(&amp;m.ID, &amp;m.Body, &amp;m.Recipient) if err == sql.ErrNoRows { empty := struct { ErrorMessage string `json:&#34;error_message&#34;` }{ &#34;No such message&#34;, } w.WriteHeader(http.StatusNotFound) json.NewEncoder(w).Encode(empty) return } json.NewEncoder(w).Encode(m) } </code></pre> <p>What&#39;s the best way to secure this API? Should I use JWT? Whats the recommended framework/toolkit for web APIs? I know I can use the stdlib, but writing this basic API using only net/http requires lots of boilerplate. </p> <hr/>**评论:**<br/><br/>whizack: <pre><ul> <li><p>you should have a consistent error handling struct that includes request data. defining anon structs for every error isn&#39;t ideal</p></li> <li><p>if you&#39;re not doing streaming json, you should use unmarshal/marshal instead</p></li> <li><p>consider wrapping the response writer with methods like Respond(interface{}) error, Header(key, value string), and Status(int) so your code reads like what you&#39;re actually doing rather than like raw http code.</p></li> <li><p>sanitize your input data. message/{id} can not possibly be valid for any value but an int64 value, but you basically allow anything to be specified</p></li> <li><p>don&#39;t panic in your handlers. sending invalid json to POST /message will crash your service</p></li> <li><p>GET /message is unbounded, appends to a zero sized array (requiring substantial growth over result size), and doesn&#39;t support range queries. Once this db has a large number of messages the query will cost an insane amount of time/memory to aggregate the results per request</p></li> <li><p>DSN is invalid if environment variables aren&#39;t set. You should be providing safe defaults for each variable (assuming a localhost db instance for example)</p></li> <li><p>You should provide handlers for unspecified routes, etc. that return valid json responses and status codes.</p></li> </ul></pre>gohacker: <pre><blockquote> <p>if you&#39;re not doing streaming json, you should use unmarshal/marshal instead</p> </blockquote> <p>json.Marshal allocates memory for the entire json, which might be huge; json.Encoder writes straight to the response.</p></pre>newbgopher: <pre><p>thanks! i&#39;ve learned a lot from your comments.</p></pre>lu_nemec: <pre><p>Hi,</p> <p>1) you don&#39;t need to have 1 db.Open() - it doesn&#39;t directly create connection, and is goroutine + thread safe, you can call db.Open() directly in the function that needs to do DB operations...</p> <p>2) no need to call defer db.Close(): <a href="https://golang.org/pkg/database/sql/#DB.Close" rel="nofollow">https://golang.org/pkg/database/sql/#DB.Close</a>. </p> <p>3) I recommend separating handlers from db operations by writing separate functions for DB - func getMessage(msgId string) error {}. This way the internal API is cleaner and you can split the database operations into separate package.</p> <p>4) most people use Gorilla toolkit for writing web applications. It is not directly a framework but rather collection of tools. You can&#39;t go wrong using it. There are several &#34;frameworks&#34; that do most of the boilerplate, but they are not as extendible - Echo is one of those for example..</p> <p>About the security - it depends on the usecase. If you have users that need to log-in before read/write operations, JWT are fine, but you have to write client JS code to use it correctly.</p></pre>heraclmene: <pre><p>1) I believe you&#39;re incorrect [0] with this statement. </p> <p>[0]<code>The returned DB is safe for concurrent use by multiple goroutines and maintains its own pool of idle connections. Thus, the Open function should be called just once. It is rarely necessary to close a DB.</code> - <a href="https://golang.org/pkg/database/sql/#Open" rel="nofollow">https://golang.org/pkg/database/sql/#Open</a></p></pre>lu_nemec: <pre><p>Ah, thanks! I somehow missed this ... oh god, this happened with http.Client not returning error on non-2xx statuses as well :D gotta pay more attention to the docs! :D</p></pre>newbgopher: <pre><p>Thanks for the response! Any opinions about go-kit? </p></pre>lu_nemec: <pre><p>Hmm, I haven&#39;t heard about it, I&#39;ll take a look but it looks fine on first glance.</p> <p>One more thing, maybe the most important - create a custom http.Server{} instance instead of the default. By default they have all Timeouts set to 0 - infinite, which is not a good idea. You should have something like this:</p> <pre><code>s := &amp;http.Server{ Addr: &#34;:8080&#34;, Handler: myHandler, ReadTimeout: 10 * time.Second, WriteTimeout: 10 * time.Second, MaxHeaderBytes: 1 &lt;&lt; 20, } log.Fatal(s.ListenAndServe()) </code></pre> <p>You can find more information here: <a href="https://golang.org/pkg/net/http/#pkg-examples" rel="nofollow">https://golang.org/pkg/net/http/#pkg-examples</a></p></pre>

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

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