• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Go网络编程之net/http包执行流程源码分析

原作者: [db:作者] 来自: [db:来源] 收藏 邀请
版权声明:本文为博主原创文章,未经博主允许不得转载。如需转载请联系本人,并标明作者和出处。 https://blog.csdn.net/huwh_/article/details/76383208
package main
import (
    "fmt"
    "log"
    "net/http"
    "strings"
)
func sayhelloName(w http.ResponseWriter, r *http.Request) {
    r.ParseForm()
    fmt.Println(r.Form)
    fmt.Println("path", r.URL.Path)
    fmt.Println("scheme", r.URL.Scheme)
    fmt.Println(r.Form["url_long"])
    for k, v := range r.Form {
        fmt.Println("key:", k)
        fmt.Println("val:", strings.Join((v), ""))
    }
    fmt.Println(w, "hello world")
}
func main() {
    http.HandleFunc("/", sayhelloName)
    err := http.ListenAndServe(":9090", nil)
    if err != nil {
        log.Fatal("ListenAndServe:", err)
    }
}

2. http包的运行机制

相关源码位于:/src/net/http/server.go

服务端的几个概念

  • Request:用户请求的信息,用来解析用户的请求信息,包括post,get,Cookie,url等信息。
  • Response:服务器需要反馈给客户端的信息。
  • Conn:用户的每次请求链接。
  • Handle:处理请求和生成返回信息的处理逻辑。

Go实现web服务的流程

  1. 创建Listen Socket,监听指定的端口,等待客户端请求到来。
  2. Listen Socket接受客户端的请求,得到Client Socket,接下来通过Client Socket与客户端通信。
  3. 处理客户端请求,首先从Client Socket读取HTTP请求的协议头,如果是POST方法,还可能要读取客户端提交的数据,然后交给相应的handler处理请求,handler处理完,将数据通过Client Socket返回给客户端。

2.1. http包执行流程图


2.2. 注册路由[HandleFunc]

http.HandlerFunc类型默认实现了ServeHTTP的接口。

 

// The HandlerFunc type is an adapter to allow the use of
// ordinary functions as HTTP handlers.  If f is a function
// with the appropriate signature, HandlerFunc(f) is a
// Handler that calls f.
type HandlerFunc func(ResponseWriter, *Request)
// ServeHTTP calls f(w, r).
func (f HandlerFunc) ServeHTTP(w ResponseWriter, r *Request) {
    f(w, r)
}
// HandleFunc registers the handler function for the given pattern
// in the DefaultServeMux.
// The documentation for ServeMux explains how patterns are matched.
func HandleFunc(pattern string, handler func(ResponseWriter, *Request)) {
    DefaultServeMux.HandleFunc(pattern, handler)
}
...
// HandleFunc registers the handler function for the given pattern.
func (mux *ServeMux) HandleFunc(pattern string, handler func(ResponseWriter, *Request)) {
    mux.Handle(pattern, HandlerFunc(handler))
}

 

Handle

Handle
// Handle registers the handler for the given pattern.
// If a handler already exists for pattern, Handle panics.
func (mux *ServeMux) Handle(pattern string, handler Handler) {
    mux.mu.Lock()
    defer mux.mu.Unlock()
 
    if pattern == "" {
        panic("http: invalid pattern " + pattern)
    }
    if handler == nil {
        panic("http: nil handler")
    }
    if mux.m[pattern].explicit {
        panic("http: multiple registrations for " + pattern)
    }
 
    mux.m[pattern] = muxEntry{explicittrue, h: handler, pattern: pattern}
 
    if pattern[0] != '/' {
        mux.hosts = true
    }
 
    // Helpful behavior:
    // If pattern is /tree/, insert an implicit permanent redirect for /tree.
    // It can be overridden by an explicit registration.
    n := len(pattern)
    if n > 0 && pattern[n-1] == '/' && !mux.m[pattern[0:n-1]].explicit {
        // If pattern contains a host name, strip it and use remaining
        // path for redirect.
        path := pattern
        if pattern[0] != 
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Go语言规格说明书 之 类型声明(Type declarations)发布时间:2022-07-10
下一篇:
Go语言练习:go语言与C语言的交互——cgo发布时间:2022-07-10
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap