protocol.go 1.02 KB
Newer Older
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
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
package protocol

import (
	"io"

	msgio "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-msgio"
)

// ID is an identifier used to write protocol headers in streams.
type ID string

// These are reserved protocol.IDs.
const (
	TestingID ID = "/p2p/_testing"
)

// WriteHeader writes a protocol.ID header to an io.Writer. This is so
// multiple protocols can be multiplexed on top of the same transport.
//
// We use go-msgio varint encoding:
//   <varint length><string name>\n
// (the varint includes the \n)
func WriteHeader(w io.Writer, id ID) error {
	vw := msgio.NewVarintWriter(w)
	s := string(id) + "\n" // add \n
	return vw.WriteMsg([]byte(s))
}

// ReadHeader reads a protocol.ID header from an io.Reader. This is so
// multiple protocols can be multiplexed on top of the same transport.
// See WriteHeader.
func ReadHeader(r io.Reader) (ID, error) {
	vr := msgio.NewVarintReader(r)
	msg, err := vr.ReadMsg()
	if err != nil {
		return ID(""), err
	}
	msg = msg[:len(msg)-1] // remove \n
	return ID(msg), nil
}