-
Notifications
You must be signed in to change notification settings - Fork 32
/
Copy pathgrpcrequest.go
60 lines (43 loc) · 1.16 KB
/
grpcrequest.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
49
50
51
52
53
54
55
56
57
58
59
60
package main
import (
"bytes"
"encoding/binary"
"io/ioutil"
"net/http"
)
const (
// header to detect if it is a grpc+json request
contentTypeGRPCJSON = "application/grpc+json"
grpcNoCompression byte = 0x00
)
func modifyRequestToJSONgRPC(r *http.Request) *http.Request {
// https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md
var body []byte
// read body so we can add the grpc prefix
if r.Body != nil {
body, _ = ioutil.ReadAll(r.Body)
}
b := make([]byte, 0, len(body)+5)
buff := bytes.NewBuffer(b)
// grpc prefix is
// 1 byte: compression indicator
// 4 bytes: content length (excluding prefix)
_ = buff.WriteByte(grpcNoCompression) // 0 or 1, indicates compressed payload
lenBytes := make([]byte, 4)
binary.BigEndian.PutUint32(lenBytes, uint32(len(body)))
_, _ = buff.Write(lenBytes)
_, _ = buff.Write(body)
// create new request
req, _ := http.NewRequest(r.Method, r.URL.String(), buff)
req.Header = r.Header
// remove content length header
req.Header.Del(headerContentLength)
return req
}
func isJSONGRPC(r *http.Request) bool {
h := r.Header.Get("Content-Type")
if h == contentTypeGRPCJSON {
return true
}
return false
}