經過教程,能夠學習並實踐使用golang構建本身的web框架。
對於REST API開發學習更加有幫助。golang
Martini 自發布起就迅速成爲最受歡迎的golang web 框架,可是它並非盡善盡美的,Martini 做者說它效率低而且設計思想並不完美,對於初學者來講並不太好。儘管如此,由於它的上手簡單使用方便仍是有一大批用戶在使用。web
目前爲止,完成web應用都是使用基礎的庫,因此個人文章也是是用基礎的庫重頭來搭建web框架。對於golang新手和老司機來講這都是最好的web實踐。cookie
在教程完成後,相信搭建會對web開發有很好的理解並獲得實踐經驗,而且會針對不一樣的實際問題,在web 框架中去試下解決方法。session
什麼是web框架?
目前有兩種類型的web框架,一種是全面形的,內置了全部的模塊功能,能讓你快速開始你的業務代碼。好比golang的Beego 和 Revel。
還有一種是是僅提供路由和少數內置功能的框架,他須要你本身完成如orm等額外的功能模塊,具備高度的定製靈活性,大多的web框架都屬於這一種類型,如martini,Goji, Gin, gocraft/web 等。框架
框架和庫的區別
究竟是用框架仍是用庫呢?我並不反對用現成的框架,可是go提供了優秀的包讓咱們輕鬆實現本身的框架。若是須要開始一個長期的項目,那麼本身來實現框架是很好的選擇。若是你剛學習golang 那麼這樣作也有助於理解golang web框架的運行原理。less
本文實現的框架包含了的功能
本教程旨在實現定製化的輕量級框架實現,而非Beego這類全能型框架。
一個框架有3個部分
路由 — 收到請求後遞交給一個handler
中間件 — 在請求以前或者以後完成一些重複的功能
handler — 處理請求,返回響應學習
中間件 handler:設計
Golang Web 框架現狀
The problem with many Go web frameworks is that these components are made for one and only one framework. They are not inter-changeable. Yes you have just routers, or just middleware systems, or just middlewares and you might use them together if they're compatible with each other. But it's a very small minority of projects and it doesn't have enough visibility except for Gorilla which has still far less followers on Github than most other frameworks.component
Go doesn't have a unified convention to handle middlewares like in Ruby (Rack), Node.js (Connect.js), Clojure (Ring) and other languages. Negroni, Goji, Gin, gocraft/web, etc, are all redefining how handlers and middlewares work. It's hard to re-use open-sourced middlewares, and it's hard to understand what are the best practices for a new developer.orm