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

介绍

通过教程,可以学习并实践使用golang构建自己的web框架。
对于REST API开发学习更加有帮助。

Martini 自发布起就迅速成为最受欢迎的golang web 框架,但是它并不是尽善尽美的,Martini 作者说它效率低并且设计思想并不完美,对于初学者来说并不太好。尽管如此,因为它的上手简单使用方便还是有一大批用户在使用。

目前为止,完成web应用都是使用基础的库,所以我的文章也是是用基础的库重头来搭建web框架。对于golang新手和老司机来说这都是最好的web实践。

在教程完成后,相信搭建会对web开发有很好的理解并得到实践经验,并且会针对不同的实际问题,在web 框架中去试下解决方法。

什么是web框架?
目前有两种类型的web框架,一种是全面形的,内置了所有的模块功能,能让你快速开始你的业务代码。比如golang的Beego 和 Revel。
还有一种是是仅提供路由和少数内置功能的框架,他需要你自己完成如orm等额外的功能模块,具有高度的定制灵活性,大多的web框架都属于这一种类型,如martini,Goji, Gin, gocraft/web 等。

框架和库的区别
到底是用框架还是用库呢?我并不反对用现成的框架,但是go提供了优秀的包让我们轻松实现自己的框架。如果需要开始一个长期的项目,那么自己来实现框架是很好的选择。如果你刚学习golang 那么这样做也有助于理解golang web框架的运行原理。

本文实现的框架包含了的功能
本教程旨在实现定制化的轻量级框架实现,而非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.

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.

    原文作者:阿西达卡
    原文地址: https://segmentfault.com/a/1190000016024602
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞