/
header.go
48 lines (42 loc) · 1.11 KB
/
header.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
// Copyright (C) 2021 Storj Labs, Inc.
// See LICENSE for copying information.
package drpcmigrate
import (
"net"
"sync"
)
// DRPCHeader is a header for DRPC connections to use. This is designed
// to not conflict with a headerless gRPC, HTTP, or TLS request.
var DRPCHeader = "DRPC!!!1"
// HeaderConn fulfills the net.Conn interface. On the first call to Write
// it will write the Header.
type HeaderConn struct {
net.Conn
once sync.Once
header string
}
// NewHeaderConn returns a new *HeaderConn that writes the provided header
// as part of the first Write.
func NewHeaderConn(conn net.Conn, header string) *HeaderConn {
return &HeaderConn{
Conn: conn,
header: header,
}
}
// Write will write buf to the underlying conn. If this is the first time Write
// is called it will prepend the Header to the beginning of the write.
func (d *HeaderConn) Write(buf []byte) (n int, err error) {
var didOnce bool
d.once.Do(func() {
didOnce = true
n, err = d.Conn.Write(append([]byte(d.header), buf...))
})
if didOnce {
n -= len(d.header)
if n < 0 {
n = 0
}
return n, err
}
return d.Conn.Write(buf)
}