【01-介绍】构建go web框架

介绍

经过教程,能够学习并实践使用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:设计

  • Error/panic
  • logging
  • security
  • sessions
  • cookies
  • Body parsing

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