墨迹一点
个人琐碎
最近比较忙,以致于很久都没有写blog了,但是,golang的水平自认为是总算入门了。
协程的个人理解
网上的说法一般都是协程是轻量级线程。
我个人认为协程的好处
- 小
- 无需在用户态和内核态切换(完全在用户态)
- 无需线程上下文切换的开销(因为之上的好处)
- 编码简单(原子操作,锁都没有了)
httpHandler优化
利用协程优化请求
这是我们原本的handler(就是监听http请求的一个对象,实现了ServeHTTP)
1type HttpHandler struct 2{ 3 Vhosts Vhosts 4 HandlerMap map[string]*http.ServeMux 5}
很明显,这里就已经是入口了,我们将其修改成
1type HttpHandler struct 2{ 3 Vhosts Vhosts 4 HandlerMap map[string]*http.ServeMux 5 Response chan *Response 6 StaticFile chan *StaticFileHandler 7 serverEnvironment map[string]string 8}
当我们遇到请求的实行,我们直接开启协程
go Run(w,r)
在Run方法中,将实现部分写入协程(即IO、计算部分),在大部分代码不变的情况下(请看1和2的分析)我们将几种错误的情况抛出一个Response对象,比如请求的是/favicon.ico
1if r.RequestURI == "/favicon.ico" { 2 httpHandler.Response <- &Response{200, map[string]string{}, nil, ""} 3 return 4}
具体的伪代码应如下:
1if something wrong { 2 gerWrongCode 3 res := generate WrongResponse 4 httpHandler.Response <- res 5 return 6} 7 8 9res := do proxy 10httpHandler.Response <- res
另外,关于静态文件,我们并不需要proxy,所以我们要告知上面,这个是静态文件,go直接处理
1 fileCode,filename := httpHandler.buildServerHttp(r, env, hm) 2 3 switch fileCode { 4 case FileCodeStatic: 5 httpHandler.StaticFile <- &StaticFileHandler{ 6 name, 7 port, 8 filename, 9 } 10 return 11 case ...... 12 }
处理协程回调
那么确定我们已经将各种IO和逻辑处理写入了协程了,这个时候,我们回到ServeHTTP方法
1 go Run(w,r) 2 for { 3 select { //进行协程的处理 4 case response := <-httpHandler.Response: //当遇到response的时候 送出结果 5 response.send(w, r) 6 case hand := <-httpHandler.StaticFile: //当遇到是静态文件的时候 直接走本身go原本的handler 7 staticHandler := httpHandler.HandlerMap[hand.Host+hand.Port] 8 staticHandler.ServeHTTP(w, r) 9 10 default: 11 respond(w, "<h1>404</h1>", 404, map[string]string{}) 12 } 13 }
添加日志
像nginx之类的,都可以写日志,那这个功能我也不能少
只需要在HttpHandler对象注入的时候加入一个log即可
1type HttpHandler struct 2{ 3 Vhosts Vhosts 4 HandlerMap map[string]*http.ServeMux 5 Response chan *Response 6 StaticFile chan *StaticFileHandler 7 serverEnvironment map[string]string 8 log *log.Logger 9} 10 11func (httpHandler *HttpHandler) SetLogger(log *log.Logger) { 12 httpHandler.log = log 13} 14 15func (httpHandler *HttpHandler) GetLogger() *log.Logger { 16 return httpHandler.log 17}
然后,代码中可以放心大胆的使用 log.*方法
至于log写文件 ,百度谷歌谢谢,他本身就带了异步IO,就不用操心了。
其他
Go实现FastCgi Proxy Client 系列(一)