Golang中HTTP服务的分析与设计详解
作者:未来谁可知 时间:2024-05-25 15:12:57
http.ListenAndServe
type Server struct {
// 请求监听地址
Addr string
// 请求核心处理函数
Handler Handler
}
http.ListenAndServe(httpAddr, nil)
// ListenAndServe always returns a non-nil error.
// 创造了一个server对象并调用ListenAndServe
func ListenAndServe(addr string, handler Handler) error {
server := &Server{Addr: addr, Handler: handler}
return server.ListenAndServe()
}
func (srv *Server) ListenAndServe() error {
// 如果关闭了http监听则直接返回ErrServerClosed
if srv.shuttingDown() {
return ErrServerClosed
}
addr := srv.Addr
if addr == "" {
addr = ":http"
}
// 开启net包的Listen监听方法,根据传入的类型返回监听的对象
ln, err := net.Listen("tcp", addr)
if err != nil {
return err
}
return srv.Serve(ln)
}
Serve方法. 接收一个监听者
func (srv *Server) Serve(l net.Listener) error {
if fn := testHookServerServe; fn != nil {
fn(srv, l) // call hook with unwrapped listener
}
origListener := l
l = &onceCloseListener{Listener: l}
defer l.Close()
if err := srv.setupHTTP2_Serve(); err != nil {
return err
}
if !srv.trackListener(&l, true) {
return ErrServerClosed
}
defer srv.trackListener(&l, false)
baseCtx := context.Background()
if srv.BaseContext != nil {
baseCtx = srv.BaseContext(origListener)
if baseCtx == nil {
panic("BaseContext returned a nil context")
}
}
var tempDelay time.Duration // how long to sleep on accept failure
// 将整个Server对象设置进ctx中,在多个goroutinue中共享
ctx := context.WithValue(baseCtx, ServerContextKey, srv)
for {
rw, err := l.Accept() // 阻塞等待连接
if err != nil {
select {
case <-srv.getDoneChan():
return ErrServerClosed
default:
}
if ne, ok := err.(net.Error); ok && ne.Temporary() {
if tempDelay == 0 {
tempDelay = 5 * time.Millisecond
} else {
tempDelay *= 2
}
if max := 1 * time.Second; tempDelay > max {
tempDelay = max
}
srv.logf("http: Accept error: %v; retrying in %v", err, tempDelay)
time.Sleep(tempDelay)
continue
}
return err
}
connCtx := ctx
if cc := srv.ConnContext; cc != nil {
connCtx = cc(connCtx, rw)
if connCtx == nil {
panic("ConnContext returned nil")
}
}
tempDelay = 0
c := srv.newConn(rw)
c.setState(c.rwc, StateNew, runHooks) // before Serve can return
go c.serve(connCtx) //Serve a new connection 建立新的连接
}
}
c.serve
这个函数主要是判断本次http请求是否升级为https,接着创建文本的reader,和写文本的buffer,再进一步读取本次的请求数据!
最后是调用关键的方法serverHandler{c.server}.ServeHttp(w,w.req)
来处理本次请求!
serverHandler
// serverHandler 代表请求对应的处理逻辑
type serverHandler struct {
srv *Server
}
// 具体的处理函数
func (sh serverHandler) ServeHTTP(rw ResponseWriter, req *Request) {
handler := sh.srv.Handler
//如果入口设置传入了`Handler`,那么调用的就是传入的,否则就是DefaultServeMux
if handler == nil {
handler = DefaultServeMux
}
if req.RequestURI == "*" && req.Method == "OPTIONS" {
handler = globalOptionsHandler{}
}
if req.URL != nil && strings.Contains(req.URL.RawQuery, ";") {
var allowQuerySemicolonsInUse int32
req = req.WithContext(context.WithValue(req.Context(), silenceSemWarnContextKey, func() {
atomic.StoreInt32(&allowQuerySemicolonsInUse, 1)
}))
defer func() {
if atomic.LoadInt32(&allowQuerySemicolonsInUse) == 0 {
sh.srv.logf("http: URL query contains semicolon, which is no longer a supported separator; parts of the query may be stripped when parsed; see golang.org/issue/25192")
}
}()
}
handler.ServeHTTP(rw, req)
}
流程梳理
上述大致调用的流程梳理完毕总结一下
创建服务->创建连接->监听请求(net.Listen)->处理请求(ServeHTTP)
标准库创建HTTP服务是通过Server对象完成的
Server对象在for循环中不断监听每一个连接
每个连接都默认开启了一个goroutine
serverHandler结构代表请求对应的逻辑,并用其ServeHTTP进行处理执行
具有默认处理Handler,DefaultServeMux
DefaultServeMux是通过map来寻找路由的
自己动手写一个serverHandler
core.go
package framework
import "net/http"
type Core struct {
}
func (c Core) ServeHTTP(writer http.ResponseWriter, request *http.Request) {
panic("implement me")
}
func NewCore() *Core {
return &Core{}
}
main.go
package main
import (
"log"
"net/http"
"testdemo1/coredemo/framework"
)
func main() {
server:=&http.Server{Addr: ":8080",Handler: framework.NewCore()}
err := server.ListenAndServe()
if err!=nil{
log.Fatal(err)
}
}
后续再往自己的serverHttp方法里自定义补充处理请求逻辑!
本文到此结束,欢迎收看下一篇
来源:https://blog.csdn.net/jiohfgj/article/details/125643145
标签:Golang,HTTP,分析,设计
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
python实现socket+threading处理多连接的方法
2021-12-16 17:54:32
![](https://img.aspxhome.com/file/2023/9/135279_0s.jpg)
Python基于mediainfo批量重命名图片文件
2021-08-20 11:31:30
![](https://img.aspxhome.com/file/2023/6/70066_0s.jpg)
浅谈MySQL存储引擎选择 InnoDB还是MyISAM
2009-05-10 20:02:00
ASP批量生成静态页面的写法(批量生成技巧iframe)
2011-02-24 11:01:00
表单相关特效整理
2013-06-29 15:42:26
Python标准库pathlib操作目录和文件
2021-08-18 02:24:57
![](https://img.aspxhome.com/file/2023/8/101598_0s.jpg)
Mootools 1.2教程(21)——类(二)
2008-12-28 20:58:00
java与php的区别浅析
2023-11-14 23:27:23
关于 MySQL 嵌套子查询中无法关联主表字段问题的解决方法
2024-01-18 23:05:28
![](https://img.aspxhome.com/file/2023/0/91440_0s.png)
SQL SERVER数据库开发之asp存储过程应用
2008-05-19 12:55:00
![](https://img.aspxhome.com/file/UploadPic/up/2008051913142215.jpg)
python绘制超炫酷动态Julia集示例
2023-10-04 12:58:49
![](https://img.aspxhome.com/file/2023/1/105861_0s.png)
Python实现Keras搭建神经网络训练分类模型教程
2023-08-06 12:33:03
![](https://img.aspxhome.com/file/2023/1/127101_0s.jpg)
浅谈Tensorflow 动态双向RNN的输出问题
2022-10-16 21:30:35
![](https://img.aspxhome.com/file/2023/3/97733_0s.jpg)
Python实现输出某区间范围内全部素数的方法
2022-04-25 10:04:50
![](https://img.aspxhome.com/file/2023/8/68318_0s.png)
*.HTC 文件的简单介绍
2008-11-24 17:36:00
mysql 控制台程序的提示符 prompt 字符串设置
2024-01-26 01:42:11
微信小程序自定义导航教程(兼容各种手机)
2024-04-30 09:53:12
![](https://img.aspxhome.com/file/2023/4/132564_0s.png)
python 实现判断ip连通性的方法总结
2023-06-24 22:36:53
MySql闪退和服务无法启动的解决方法
2024-01-21 07:53:12
![](https://img.aspxhome.com/file/2023/1/121591_0s.jpg)
python聊天室(虽然很简洁,但是可以用)
2021-05-21 01:10:46
![](https://img.aspxhome.com/file/2023/0/84120_0s.png)