為什么是Martini
===============
在上一版 [Go語言博客實踐][1] 中, 作者提到不使用框架來完成一個 Blog 系統. 現在選擇 [Martini][2] 作為基礎框架確實和 Martini 設計的獨特性有關. Martini 的核心 [Injector][3] 實現了[依賴注入][4] ( 參見 [控制反轉][5] ).
這里有兩篇博客可供參考 [Martini的工作方式][6] 和 [Martini中的Handler][7].
簡單的說 Injector 通過 reflect 削弱了合作對象間引用依賴.
對于 Martini 的使用可以簡單總結為:
- Martini 對象方法 Map/MapTo/Use/Handlers/Action 非并發安全, 服務器運行前使用.
- Router 對象也是非并發安全的, 服務器運行前使用.
- Context 對象是在 http Request 時動態創建的.
- 所有要使用的對象必須先 Map/MapTo.
- 對 http.ResponseWriter 任何的 Write 都會完結響應. 內部方法是終止了響應 Handler.
- 善用 Context 對象的 Next 方法會產生奇效.
上一版本因為不能找到 "解耦" 的框架而放棄使用框架. Martini 在 Injector 的支持下為"解耦"提供了可能. 這正是筆者希望的.
Package選擇與修改
=================
- Martini社區 [martini-contrib][8]
Martini 社區貢獻的 package, 可能會使用一些.如果您研究了 Martini 和這些 contrib package, 您會發現真的解耦了.
- 角色控制 [accessflags][9]
角色控制是應用中的常見需求, accessflags 基于 Martini 實現了一個通過 interger 標記值控制 Martini.Handler 是否允許訪問. 可以用于角色控制. (已被社區收錄)
- 配置文件支持 [tom-toml][10]
筆者重新寫了一個 TOML 解析器 tom-toml, 參見文章[有關tom-toml的一些事兒][11], 和第六章的內容.
- 數據庫操作 [typepress/db][12]
[upper.io/db][13] 是 [gosexy/db][14] 的重構版本. 代碼質量很高. 但是包路徑問題同樣給 import 造成了問題. 為方便, 筆者 fork 了一個 github 版本 [typepress/db][15].
upper.io/db 為常見的 SQL/NoSQL 數據庫提供了統一的調用接口, 這是非常難能可貴的.
- 日志支持 [typepress/log][16]
typepress/log 學習了 [uniqush/log ][17] 的一些好想法重新構建的.
typepress/log 支持日志分割, 并實現了一個 file 日志, 一個 email 日志.
- template 模板
可能會有幾個備選版本 martini-contrib 中有[render][18], 筆者寫有 [template][19].
- 國際化支持 [i18n][20]
這是一個簡潔的 i18n 支持接口, 仿照 fmt.Sprint, fmt.Sprintf 的形式.
在使用中即便暫時沒有國際化支持的需求, 使用 i18n 所帶來的消耗也是極小的. 完全可以當作 fmt.Sprint, fmt.Sprintf 使用.
依賴注入
========
Martini 的核心就是實現依賴注入, 高度解耦. 依據依賴注入的思路, 上述的 package 被替換掉應該不是一件復雜的事情. 隨時引入依賴注入也應該很容易. 也許吧, 實踐中我會關注這個事情.
[1]: https://github.com/achun/Go-Blog-In-Action/tree/master
[2]: https://github.com/codegangsta/martini "Martini"
[3]: https://github.com/codegangsta/inject "inject"
[4]: http://en.wikipedia.org/wiki/Dependency_injection "Dependency injection"
[5]: http://zh.wikipedia.org/wiki/控制反轉 "控制反轉"
[6]: http://my.oschina.net/achun/blog/192912 "Martini的工作方式"
[7]: http://my.oschina.net/achun/blog/197546 "Martini中的Handler"
[8]: https://github.com/martini-contrib "martini-contrib"
[9]: https://github.com/typepress/accessflags
[10]: https://github.com/achun/tom-toml
[11]: http://my.oschina.net/achun/blog/196953 "有關tom-toml的一些事兒"
[12]: https://github.com/typepress/db
[13]: https://github.com/upper/db
[14]: https://github.com/gosexy/db
[15]: https://github.com/typepress/db
[16]: https://github.com/typepress/log
[17]: https://github.com/uniqush/log
[18]: https://github.com/martini-contrib/render
[19]: https://github.com/achun/template
[20]: https://github.com/typepress/i18n