golang 中的http包详解

RESTful,是目前最为流行的一种互联网软件架构。URI表示一个资源,表现层用html、json、xml等格式输出,客户端和服务器互动http协议里的Get ,Post,Put等方法分别对应不同的操作。

restful架构图:
这里写图片描述

首先来看看request和response的header中有哪些内容:

request

Header 解释 示例
Accept 指定客户端能够接收的内容类型 Accept: text/plain, text/html
Accept-Charset 浏览器可以接受的字符编码集。 Accept-Charset: iso-8859-5
Accept-Encoding 指定浏览器可以支持的web服务器返回内容压缩编码类型。 Accept-Encoding: compress, gzip
Accept-Language 浏览器可接受的语言 Accept-Language: en,zh
Accept-Ranges 可以请求网页实体的一个或者多个子范围字段 Accept-Ranges: bytes
Authorization HTTP授权的授权证书 Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==
Cache-Control 指定请求和响应遵循的缓存机制 Cache-Control: no-cache
Connection 表示是否需要持久连接。(HTTP 1.1默认进行持久连接) Connection: close
Cookie HTTP请求发送时,会把保存在该请求域名下的所有cookie值一起发送给web服务器。 Cookie: $Version=1; Skin=new;
Content-Length 请求的内容长度 Content-Length: 348
Content-Type 请求的与实体对应的MIME信息 Content-Type: application/x-www-form-urlencoded
Date 请求发送的日期和时间 Date: Tue, 15 Nov 2010 08:12:31 GMT
Expect 请求的特定的服务器行为 Expect: 100-continue
From 发出请求的用户的Email From: [email protected]
Host 指定请求的服务器的域名和端口号 Host: www.zcmhi.com
If-Match 只有请求内容与实体相匹配才有效 If-Match: “737060cd8c284d8af7ad3082f209582d”
If-Modified-Since 如果请求的部分在指定时间之后被修改则请求成功,未被修改则返回304代码 If-Modified-Since: Sat, 29 Oct 2010 19:43:31 GMT
If-None-Match 如果内容未改变返回304代码,参数为服务器先前发送的Etag,与服务器回应的Etag比较判断是否改变 If-None-Match: “737060cd8c284d8af7ad3082f209582d”
If-Range 如果实体未改变,服务器发送客户端丢失的部分,否则发送整个实体。参数也为Etag If-Range: “737060cd8c284d8af7ad3082f209582d”
If-Unmodified-Since 只在实体在指定时间之后未被修改才请求成功 If-Unmodified-Since: Sat, 29 Oct 2010 19:43:31 GMT
Max-Forwards 限制信息通过代理和网关传送的时间 Max-Forwards: 10
Pragma 用来包含实现特定的指令 Pragma: no-cache
Proxy-Authorization 连接到代理的授权证书 Proxy-Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==
Range 只请求实体的一部分,指定范围 Range: bytes=500-999
Referer 先前网页的地址,当前请求网页紧随其后,即来路 Referer: http://www.zcmhi.com/archives/71.html
TE 客户端愿意接受的传输编码,并通知服务器接受接受尾加头信息 TE: trailers,deflate;q=0.5
Upgrade 向服务器指定某种传输协议以便服务器进行转换(如果支持) Upgrade: HTTP/2.0, SHTTP/1.3, IRC/6.9, RTA/x11
User-Agent User-Agent的内容包含发出请求的用户信息 User-Agent: Mozilla/5.0 (Linux; X11)
Via 通知中间网关或代理服务器地址,通信协议 Via: 1.0 fred, 1.1 nowhere.com (Apache/1.1)
Warning 关于消息实体的警告信息 Warn: 199 Miscellaneous warning

response

Header 解释 示例
Accept-Ranges 表明服务器是否支持指定范围请求及哪种类型的分段请求 Accept-Ranges: bytes
Age 从原始服务器到代理缓存形成的估算时间(以秒计,非负) Age: 12
Allow 对某网络资源的有效的请求行为,不允许则返回405 Allow: GET, HEAD
Cache-Control 告诉所有的缓存机制是否可以缓存及哪种类型 Cache-Control: no-cache
Content-Encoding web服务器支持的返回内容压缩编码类型。 Content-Encoding: gzip
Content-Language 响应体的语言 Content-Language: en,zh
Content-Length 响应体的长度 Content-Length: 348
Content-Location 请求资源可替代的备用的另一地址 Content-Location: /index.htm
Content-MD5 返回资源的MD5校验值 Content-MD5: Q2hlY2sgSW50ZWdyaXR5IQ==
Content-Range 在整个返回体中本部分的字节位置 Content-Range: bytes 21010-47021/47022
Content-Type 返回内容的MIME类型 Content-Type: text/html; charset=utf-8
Date 原始服务器消息发出的时间 Date: Tue, 15 Nov 2010 08:12:31 GMT
ETag 请求变量的实体标签的当前值 ETag: “737060cd8c284d8af7ad3082f209582d”
Expires 响应过期的日期和时间 Expires: Thu, 01 Dec 2010 16:00:00 GMT
Last-Modified 请求资源的最后修改时间 Last-Modified: Tue, 15 Nov 2010 12:45:26 GMT
Location 用来重定向接收方到非请求URL的位置来完成请求或标识新的资源 Location: http://www.zcmhi.com/archives/94.html
Pragma 包括实现特定的指令,它可应用到响应链上的任何接收方 Pragma: no-cache
Proxy-Authenticate 它指出认证方案和可应用到代理的该URL上的参数 Proxy-Authenticate: Basic
refresh 应用于重定向或一个新的资源被创造,在5秒之后重定向(由网景提出,被大部分浏览器支持) Refresh: 5; url=
http://www.zcmhi.com/archives/94.html
Retry-After 如果实体暂时不可取,通知客户端在指定时间之后再次尝试 Retry-After: 120
Server web服务器软件名称 Server: Apache/1.3.27 (Unix) (Red-Hat/Linux)
Set-Cookie 设置Http Cookie Set-Cookie: UserID=JohnDoe; Max-Age=3600; Version=1
Trailer 指出头域在分块传输编码的尾部存在 Trailer: Max-Forwards
Transfer-Encoding 文件传输编码 Transfer-Encoding:chunked
Vary 告诉下游代理是使用缓存响应还是从原始服务器请求 Vary: *
Via 告知代理客户端响应是通过哪里发送的 Via: 1.0 fred, 1.1 nowhere.com (Apache/1.1)
Warning 警告实体可能存在的问题 Warning: 199 Miscellaneous warning
WWW-Authenticate 表明客户端请求实体应该使用的授权方案 WWW-Authenticate: Basic

客户端首先构造client结构体:

type Client struct {

    Transport RoundTripper//真正发送request并且获取response的实现
   CheckRedirect func(req *Request, via []*Request) error//redirect之前的调用的handler
    Jar CookieJar//存放cookie信息
    Timeout time.Duration//连接,重定向,读取response等的时间限制
}

http包提供defultclient为client的空实现。

实现第一个字段RoundTripper这个接口的为Transport,可以用于不同协议,比如file,ftp等使用RegisterProtocol(scheme string, rt RoundTripper)注册协议并提供roundtripper,transport中的map缓存了已经创建的persistConn(tcp连接),多协程并发使用一个client是安全的:

// Transport is an implementation of RoundTripper that supports HTTP,
// HTTPS, and HTTP proxies (for either HTTP or HTTPS with CONNECT).
// Transport can also cache connections for future re-use.
type Transport struct {
    idleMu     sync.Mutex
    wantIdle   bool // user has requested to close all idle conns
    idleConn   map[connectMethodKey][]*persistConn
    idleConnCh map[connectMethodKey]chan *persistConn//多个请求共用连接时的管道通信

    reqMu       sync.Mutex
    reqCanceler map[*Request]func()

    altMu    sync.RWMutex
    altProto map[string]RoundTripper // nil or map of URI scheme => RoundTripper


    Proxy func(*Request) (*url.URL, error)


    Dial func(network, addr string) (net.Conn, error)//没有加密的tcp连接


    DialTLS func(network, addr string) (net.Conn, error)//TSL握手,TCP握手

    // TLSClientConfig specifies the TLS configuration to use with
    // tls.Client. If nil, the default configuration is used.
    TLSClientConfig *tls.Config

    // TLSHandshakeTimeout specifies the maximum amount of time waiting to
    // wait for a TLS handshake. Zero means no timeout.
    TLSHandshakeTimeout time.Duration

    // DisableKeepAlives, if true, prevents re-use of TCP connections
    // between different HTTP requests.
    DisableKeepAlives bool

    DisableCompression bool//是否压缩

    // MaxIdleConnsPerHost, if non-zero, controls the maximum idle
    // (keep-alive) to keep per-host.  If zero,
    // DefaultMaxIdleConnsPerHost is used.
    MaxIdleConnsPerHost int

    ResponseHeaderTimeout time.Duration//request构造成功后获取response header的时间限制不包括读取response body
}

CookieJar 在request中设置cookie信息。Timeout设置从获取连接,重定向到获取response的时间限制。
创建client完毕后创建Request,body通常是采用strings.NewReader函数,将一个string类型转化为io.Reader类型,或者bytes.NewBuffer函数,将[]byte类型转化为io.Reader类型,request header中的Content-Type为文件格式,若要发送json文件值为”application/json; charset=utf-8”,表单为application/x-www-form-urlencoded:

func NewRequest(method, urlStr string, body io.Reader) (*Request, error) {
    u, err := url.Parse(urlStr)//获取url
    if err != nil {
        return nil, err
    }
    rc, ok := body.(io.ReadCloser)
    if !ok && body != nil {
        rc = ioutil.NopCloser(body)//转换成close操作为空的ReadCloser
    }
    req := &Request{
        Method:     method,
        URL:        u,
        Proto:      "HTTP/1.1",
        ProtoMajor: 1,
        ProtoMinor: 1,
        Header:     make(Header),
        Body:       rc,
        Host:       u.Host,
    }
    if body != nil {
        switch v := body.(type) {
        case *bytes.Buffer:
            req.ContentLength = int64(v.Len())
        case *bytes.Reader:
            req.ContentLength = int64(v.Len())
        case *strings.Reader:
            req.ContentLength = int64(v.Len())
        }
    }

    return req, nil
}

method可以为restful中的各种操作方法。client中的Do方法发送request,send方法中将客户端的cookie信息设置在request header中,将response返回的cookie设置在客户端的信息中:

func (c *Client) Do(req *Request) (resp *Response, err error) {
    if req.Method == "GET" || req.Method == "HEAD" {
        return c.doFollowingRedirects(req, shouldRedirectGet)
    }
    if req.Method == "POST" || req.Method == "PUT" {
        return c.doFollowingRedirects(req, shouldRedirectPost)
    }
    return c.send(req)
}
func (c *Client) send(req *Request) (*Response, error) {
    if c.Jar != nil {
        for _, cookie := range c.Jar.Cookies(req.URL) {
            req.AddCookie(cookie)
        }
    }
    resp, err := send(req, c.transport())
    if err != nil {
        return nil, err
    }
    if c.Jar != nil {
        if rc := resp.Cookies(); len(rc) > 0 {
            c.Jar.SetCookies(req.URL, rc)
        }
    }
    return resp, err
}
// send issues an HTTP request.
// Caller should close resp.Body when done reading from it.
func send(req *Request, t RoundTripper) (resp *Response, err error) {
    ...
    if u := req.URL.User; u != nil && req.Header.Get("Authorization") == "" {
        username := u.Username()
        password, _ := u.Password()
        req.Header.Set("Authorization", "Basic "+basicAuth(username, password))//验证信息放入header
    }
    resp, err = t.RoundTrip(req)
    if err != nil {
        if resp != nil {
            log.Printf("RoundTripper returned a response & error; ignoring response")
        }
        return nil, err
    }
    return resp, nil
}

client的Get(url string),Post(url string, bodyType string, body io.Reader)等方法都对newRequest进行了封装。

而使用http包中的Get(url string),Post(url string, bodyType string, body io.Reader)等方法都是用了DefaultClient来调用client的对用方法。

最后重点讲一下真正发送request并且获取response的Transport。正如上面所讲这个结构体中将http keep-alive长连接缓存下来重复利用。

func (t *Transport) RoundTrip(req *Request) (resp *Response, err error) {


    treq := &transportRequest{Request: req}
    cm, err := t.connectMethodForRequest(treq)
    ...
    pconn, err := t.getConn(req, cm)
    ...
    return pconn.roundTrip(treq)
}

func (t *Transport) getConn(req *Request, cm connectMethod) (*persistConn, error) {
    if pc := t.getIdleConn(cm); pc != nil {
        // set request canceler to some non-nil function so we
        // can detect whether it was cleared between now and when
        // we enter roundTrip
        t.setReqCanceler(req, func() {})
        return pc, nil
    }

    type dialRes struct {
        pc  *persistConn
        err error
    }
    dialc := make(chan dialRes)

    // Copy these hooks so we don't race on the postPendingDial in
    // the goroutine we launch. Issue 11136.
    prePendingDial := prePendingDial
    postPendingDial := postPendingDial

    handlePendingDial := func() {
        if prePendingDial != nil {
            prePendingDial()
        }
        go func() {
            if v := <-dialc; v.err == nil {
                t.putIdleConn(v.pc)
            }
            if postPendingDial != nil {
                postPendingDial()
            }
        }()
    }

    cancelc := make(chan struct{})
    t.setReqCanceler(req, func() { close(cancelc) })

    go func() {
        pc, err := t.dialConn(cm)
        dialc <- dialRes{pc, err}
    }()

    idleConnCh := t.getIdleConnCh(cm)
    select {
    case v := <-dialc:
        // Our dial finished.
        return v.pc, v.err
    case pc := <-idleConnCh:
        // Another request finished first and its net.Conn
        // became available before our dial. Or somebody
        // else's dial that they didn't use.
        // But our dial is still going, so give it away
        // when it finishes:
        handlePendingDial()
        return pc, nil
    case <-req.Cancel:
        handlePendingDial()
        return nil, errors.New("net/http: request canceled while waiting for connection")
    case <-cancelc:
        handlePendingDial()
        return nil, errors.New("net/http: request canceled while waiting for connection")
    }
}

getconn先用请求的host地址,协议类型,代理作为key获取已经存在的长连接,如果不存在则开始建立连接.Transport中有两种dial方式,dialtls(https协议)和dial(http协议),https协议在网络层和应用层中间加入了会话层使用ssl/tls.优先使用构造Transport实例时提供的dial方法,否则使用net.Dial。(底层其实有很多内容,看的不太明白,有空得再仔细看看源码中http协议底层实现。)

http包还提供了file协议的filetransport:

func (t fileTransport) RoundTrip(req *Request) (resp *Response, err error) {
    rw, resc := newPopulateResponseWriter()
    go func() {
        t.fh.ServeHTTP(rw, req)
        rw.finish()
    }()
    return <-resc, nil
}
func (f *fileHandler) ServeHTTP(w ResponseWriter, r *Request) {
    upath := r.URL.Path
    if !strings.HasPrefix(upath, "/") {
        upath = "/" + upath
        r.URL.Path = upath
    }
    serveFile(w, r, f.root, path.Clean(upath), true)
}
func serveFile(w ResponseWriter, r *Request, fs FileSystem, name string, redirect bool) {
    const indexPage = "/index.html"
...
    f, err := fs.Open(name)
    ...

    d, err1 := f.Stat()//获取文件的fileinfo
    ...

    // use contents of index.html for directory, if present
    if d.IsDir() {
        index := strings.TrimSuffix(name, "/") + indexPage
        ff, err := fs.Open(index)//默认为index file
        if err == nil {
            defer ff.Close()
            dd, err := ff.Stat()
            if err == nil {
                name = index
                d = dd
                f = ff
            }
        }
    }
...
    // serveContent will check modification time
    sizeFunc := func() (int64, error) { return d.Size(), nil }
    serveContent(w, r, d.Name(), d.ModTime(), sizeFunc, f)
}
func serveContent(w ResponseWriter, r *Request, name string, modtime time.Time, sizeFunc func() (int64, error), content io.ReadSeeker) {
    if checkLastModified(w, r, modtime) {//if-modified-since之后没有修改直接返回304
        return
    }
    rangeReq, done := checkETag(w, r, modtime)//if-none-match的etag与服务器返回的etag相同则直接返回304
    if done {
        return
    }

    code := StatusOK
    ...

猜你喜欢

转载自blog.csdn.net/yuwenqi123456/article/details/71055368