http.ListenAndServe
serverHandler
流程梳理
自己动手写一个serverHandler
core.go
main.go
http.ListenAndServetype 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 代表请求对应的处理逻辑
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.gopackage 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方法里自定义补充处理请求逻辑!
本文到此结束,欢迎收看下一篇
到此这篇关于Golang中HTTP服务的分析与设计详解的文章就介绍到这了,更多相关Golang HTTP服务内容请搜索软件开发网以前的文章或继续浏览下面的相关文章希望大家以后多多支持软件开发网!