Go1.9不使用http2提高http传输效率

内部应用对外提供httpAPI,QPS提不上去,于是对接口进行了改造,将短链接改成长连接,在长连接上做数据交互.QPS有了显著提高,代码片段.内部实现是自定义解析http的,类似于fasthttp的方法,需要时解析,这里是用标准库的方法做的小实例

package main

import (
    "bufio"
    "io"
    "log"
    "net"
    "net/http"
    "os"
    "os/signal"
    "time"
)

func main() {
    lis, err := net.Listen("tcp", ":1789")
    if err != nil {
        log.Fatalf("Listen port error:%s\n", err.Error())
    }

    var (
        sigChan = make(chan os.Signal, 1)
    )

    signal.Notify(sigChan, os.Interrupt, os.Kill)

    go func() {
        <-sigChan
        lis.Close()
    }()
    server(lis)
}

func server(lis net.Listener) {
    for {
        conn, err := lis.Accept()
        if err != nil {
            opt, ok := err.(*net.OpError)
            if ok {
                if opt.Err.Error() == "use of closed network connection" {
                    return
                }
            }
            //在这里可以控制错误时等待时间
            log.Println(err.Error())
            continue
        }
        //写时候要加锁,这里不做实现
        go handler(conn)
    }
}

func handler(conn net.Conn) {
    buf := bufio.NewReader(conn)
    for {
        req, err := http.ReadRequest(buf)
        if err != nil {
            log.Printf("Read requst error:%s\n", err.Error())
            break
        }
        go handler_req(conn, req)
    }
    conn.Close()
}

func handler_req(w io.Writer, req *http.Request) {
    log.Printf("Remoteddr:%s URI:%s\n", req.RemoteAddr, req.RequestURI)
    resp := NewRespnse(req)
    resp.Write(w)
}

func NewRespnse(req *http.Request) *http.Response {
    resp := &http.Response{Request: req, ProtoMajor: 1, ProtoMinor: 1, StatusCode: http.StatusOK, Header: make(http.Header), ContentLength: 0}
    resp.Header.Set("Server", "secrecy")
    resp.Header.Set("Connection", "keep-alive")
    resp.Header.Set("Content-Type", "text/html;charset=utf-8")
    resp.Header.Set("Date", time.Now().String())
    return resp
}

你可能感兴趣的:(Golang)