Golang TCP服务器:如何写入HTTP2数据

时间:2018-08-24 10:33:56

标签: go tcp http2

我是HTTP / 2.0的新手,我试图建立一个用Golang编写的TCP服务器,该服务器可以接收和写入HTTP / 2.0帧。我无法将任何数据写回客户端。

以下代码段显示了如何处理请求。

conn, err := l.Accept()
if err != nil {
    log.Fatal("could not accept connection:", err)
}
defer conn.Close()

// Every connection starts with a connection preface send first, which has to be read prior
// to reading any frames (RFC 7540, section 3.5)
const preface = "PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n"
b := make([]byte, len(preface))
if _, err := io.ReadFull(conn, b); err != nil {
    log.Fatal("could not read from connection:", err)
}
if string(b) != preface {
    log.Fatal("invalid preface")
}

framer := http2.NewFramer(conn, conn)

// Read client request (SETTINGS and HEADERS)
readFrames(framer)

// Send empty SETTINGS frame to the client
framer.WriteRawFrame(http2.FrameSettings, 0, 0, []byte{})

// Read clients response (contains empty SETTINGS with END_STREAM flag)
readFrames(framer)

// Prepare HEADERS
hbuf := bytes.NewBuffer([]byte{})
encoder := hpack.NewEncoder(hbuf)
encoder.WriteField(hpack.HeaderField{Name: ":status:", Value: "200"})
encoder.WriteField(hpack.HeaderField{Name: "date", Value: time.Now().UTC().Format(http.TimeFormat)})
encoder.WriteField(hpack.HeaderField{Name: "content-length", Value: strconv.Itoa(len("ok"))})
encoder.WriteField(hpack.HeaderField{Name: "content-type", Value: "text/html"})

// Write HEADERS frame 
err = framer.WriteHeaders(http2.HeadersFrameParam{StreamID: 2, BlockFragment: hbuf.Bytes(), EndHeaders: true})
if err != nil {
    log.Fatal("could not write headers: ", err)
}

// Clients response contains GOAWAY
readFrames(framer)

framer.WriteData(2, true, []byte("ok"))
conn.Close()

完整的服务器可以在这里找到:https://play.golang.org/p/ONA_OoyAMg-

通过卷曲来调用它:

curl -kv https://127.0.0.1:8080 --http2

据我所知,在“设置”帧之后,连接应已准备好进行流量。应该通过发送HEADERS帧来打开流,然后可以在打开的流上发送DATA帧。但是,在发送HEADERS帧后,我收到以下错误消息:

curl: (16) Error in the HTTP2 framing layer

客户以GOAWAY回应。

1 个答案:

答案 0 :(得分:1)

我发现了这个问题,如果实际上有两个。我在本文中发现了两个问题:https://www.example.com/admin/

首先,包含状态码的必需响应标头应为:status,而不是:status:

最后,我没有对发出请求的同一流ID进行响应,而是尝试打开一个新流。

因此,我应该遍历请求帧,查找流ID,并将其用于写出响应头。

// Read client request (SETTINGS and HEADERS)
readFrames(framer)
var streamID uint32
for _, frame := range frames {
    if headersframe, ok := frame.(*http2.HeadersFrame); ok {
        streamID = headersframe.StreamID
    }
}

//... Prepare headers

// Write HEADERS frame 
err = framer.WriteHeaders(http2.HeadersFrameParam{StreamID: streamID, BlockFragment: hbuf.Bytes(), EndHeaders: true})
if err != nil {
    log.Fatal("could not write headers: ", err)
}

framer.WriteData(streamID, true, []byte("ok"))
conn.Close()