大家好,從今天起,我們一起來學習 Echo 框架。
這幾年,隨著 Go 語言的發展,各種 Web 框架也出現了。常言道:沒有選擇是一種無奈,有選擇是一種痛苦。所以,大家總是問:Web 框架大佬推薦哪個?
這一年,國內推薦 Gin 的人很多,也讓 Gin 的 Star 數增加到了 39.4k+(2020-06-29),網絡上 Gin 相關的教程也很多。總體來說,Gin、Echo 等都比較輕量,易用性也差距不大,而 Gin 最大的一個優勢是直接使用了 httprouter,因此性能很高,從 Gin 項目中的 Benchmark 表格可以看出:
Benchmark name(1)(2)(3)(4)BenchmarkGin_GithubAll300004837500BenchmarkAce_GithubAll1000013405913792167BenchmarkBear_GithubAll500053444586448943BenchmarkBeego_GithubAll300059244474705812BenchmarkBone_GithubAll20069573086987848453BenchmarkDenco_GithubAll1000015881920224167BenchmarkEcho_GithubAll100001547006496203BenchmarkGocraftWeb_GithubAll30005708061316561686BenchmarkGoji_GithubAll200081803456112334BenchmarkGojiv2_GithubAll200012139732747683712BenchmarkGoJsonRest_GithubAll20007857961343712737BenchmarkGoRestful_GithubAll30052381886896724519BenchmarkGorillaMux_GithubAll100102577262118402272BenchmarkHttpRouter_GithubAll2000010541413792167BenchmarkHttpTreeMux_GithubAll1000031993465856671BenchmarkKocha_GithubAll1000020944223304843BenchmarkLARS_GithubAll200006256500Benchmarkmacaron_GithubAll200011612702041942000BenchmarkMartini_GithubAll20099917132265492325BenchmarkPat_GithubAll2005590793149956827435BenchmarkPossum_GithubAll1000031976884448609BenchmarkR2router_GithubAll1000030513477328979BenchmarkRivet_GithubAll1000013213416272167BenchmarkTango_GithubAll3000552754638261618BenchmarkTigerTonic_GithubAll100014394832391045374BenchmarkTraffic_GithubAll10011383067265932921848BenchmarkVulcan_GithubAll500039425319894609
- (1): Total Repetitions achieved in constant time, higher means more confident result
- (2): Single Repetition Duration (ns/op), lower is better
- (3): Heap Memory (B/op), lower is better
- (4): Average Allocations per Repetition (allocs/op), lower is better
然而我下載 Gin 上提供的測試代碼,發現 Echo 性能更好(或至少不比 Gin 差),下面是和上面對應的在我本地的測試(MacOS 4核 8G),測試代碼:
https://github.com/julienschmidt/go-http-routing-benchmark
BenchmarkEcho_GithubAll 35334 34642 ns/op 0 B/op 0 allocs/op
BenchmarkGin_GithubAll 34724 34696 ns/op 0 B/op 0 allocs/op
而且 Echo 上提供的測試結果也表明了這一點(我本地試驗了,確實如此):

為什么是 Echo?
截止 2020 年 06 月 29 日,Gin 的 Star 數高達 39.4k+,而 Echo 的 Star 數才 17.5k+,為什么不是選擇講解 Gin 而是 Echo?
我想理由有如下幾個:
- Gin 的教程不少,但 Echo 教程不多;
- Echo 1.x 時候,我就用在了 studygolang.com 上,現在更新到了 4.x,studygolang 也升級到了 Echo 最新版;
- 兩者都是輕量級框架,而且性能不分伯仲,甚至 Echo 更勝一籌;
- Gin 的 Star 數這么高,跟大家的推廣很有關系;作為最早一批使用 Echo 的用戶,我認為有必要推廣下 Echo,好東西希望更多人學習、使用;
計劃
本系列教程計劃包含如下部分:
一、基礎教程篇
講解 Echo 的基礎使用
二、定制篇
講解如何定制或擴展 Echo
三、實戰篇
通過一個項目講解 Echo 的實戰
四、源碼學習篇
分析 Echo 的源碼,了解它的設計,看看能領悟、學習到什么