您的位置:首页 > 理论基础 > 计算机网络

Go http源码解析(一)

2015-08-09 23:08 1211 查看

Go web之旅

此篇开始将开启Go web之旅,我将这趟旅途分为三个子旅程:

源码解析

框架解读

中间件使用

所以在这趟旅途中我们将领略源码之雄伟,框架之奇艳,中间件之灵秀。在接下来的时间里我会按照上面的目录依次讲解。

现在开始踏上Go web的旅程。

func firstHandler(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, "Hello,world")
}
func main() {
http.HandleFunc("/hello", firstHandler)
http.ListenAndServe(":8080", nil)
}


在main函数中,http.HandleFunc设置所有对路径为/hello请求的处理函数为firstHandler.

接下来调用http.ListenAndServe,在8080端口开始监听将阻塞,直到退出。

我们将以源码解析作为整个旅程的开篇。

Go语言作为互联网中的c语言,他让web开发简洁到不能再简洁了。首先我们来介绍他让web开发变得简易所涉及的最重要的包(package)(当遇到包时一般直接用package表示)之一http.

package http在service.go中。
// HTTP server.  See RFC 2616.
package http
//声明一个Handler接口,若某函数实现了ServeHTTP函数就实现了该接口
type Handler interface {
ServeHTTP(ResponseWriter, *Request)
}


那我们该如何实现该接口呢?

其实在service.go中他已经默认实现了该函数

type ServeMux struct {//定义路由规则
mu    sync.RWMutex//锁机制,因为并发处理需要一个锁
m     map[string]muxEntry//路由,采用map结构
hosts bool // whether any patterns contain hostnames
}
type muxEntry struct {//路由
explicit bool   //是否精准匹配
h        Handler//路由匹配后,所选择的处理
pattern  string //匹配字符串
}

// ServeHTTP dispatches the request to the handler whose
// pattern most closely matches the request URL.
//路由结构ServeMux实现ServeHTTP函数
func (mux *ServeMux) ServeHTTP(w ResponseWriter, r *Request) {
if r.RequestURI == "*" {
if r.ProtoAtLeast(1, 1) {
w.Header().Set("Connection", "close")
}
w.WriteHeader(StatusBadRequest)
return
}
h, _ := mux.Handler(r)
h.ServeHTTP(w, r)
}


从godoc提示可以知道,当一个请求来时,先进行路由匹配,这一过程由ServeMux.m中的string来匹配完成。

匹配成功后选择muxEntry.h所对应的handler进行处理,而这一步是调用ServeHTTP实现。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: