-
Notifications
You must be signed in to change notification settings - Fork 0
/
prottp.go
237 lines (198 loc) · 5.46 KB
/
prottp.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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
package prottp
import (
"bytes"
"fmt"
"io/ioutil"
"net/http"
"strconv"
"strings"
"github.com/golang/protobuf/jsonpb"
"github.com/golang/protobuf/proto"
"github.com/golang/protobuf/ptypes/empty"
"github.com/theplant/appkit/kerrs"
"github.com/theplant/appkit/server"
"google.golang.org/grpc"
)
type Service interface {
Description() grpc.ServiceDesc
}
type HTTPStatusError interface {
HTTPStatusCode() int
}
type ErrorResponse interface {
Message() proto.Message
}
type ErrorWithStatus interface {
HTTPStatusError
ErrorResponse
error
}
type respError struct {
statusCode int
body proto.Message
}
func (re *respError) Message() proto.Message {
return re.body
}
func (re *respError) HTTPStatusCode() int {
if re.statusCode == 0 {
return http.StatusUnprocessableEntity
}
return re.statusCode
}
func (re *respError) Error() string {
return "prottp error"
}
func NewError(statusCode int, body proto.Message) ErrorWithStatus {
return &respError{statusCode: statusCode, body: body}
}
func Handle(mux *http.ServeMux, service Service, mws ...server.Middleware) {
HandleWithInterceptor(mux, service, nil, mws...)
}
func Wrap(service Service) http.Handler {
return WrapWithInterceptor(service, nil)
}
func WrapWithInterceptor(service Service, interceptor grpc.UnaryServerInterceptor) http.Handler {
mux := http.NewServeMux()
d := service.Description()
for _, desc := range d.Methods {
fmt.Println("/" + d.ServiceName + "/" + desc.MethodName)
mux.Handle("/"+desc.MethodName, wrapMethod(service, desc, interceptor))
}
return mux
}
func HandleWithInterceptor(mux *http.ServeMux, service Service, interceptor grpc.UnaryServerInterceptor, mws ...server.Middleware) {
sn := service.Description().ServiceName
fmt.Println("/" + sn)
hd := WrapWithInterceptor(service, interceptor)
if len(mws) > 0 {
hd = server.Compose(mws...)(hd)
}
mux.Handle("/"+sn+"/", http.StripPrefix("/"+sn, hd))
}
var marshaler = jsonpb.Marshaler{
EnumsAsInts: false,
EmitDefaults: false,
Indent: "\t",
OrigName: true,
}
var unmarshaler = jsonpb.Unmarshaler{
AllowUnknownFields: false,
}
const jsonContentType = "application/json"
const xprottpContentType = "application/x.prottp"
const protoContentType = "application/proto"
func isMimeTypeJSON(contentType string) bool {
return strings.Index(strings.ToLower(contentType), jsonContentType) >= 0
}
func isContentTypeJSON(r *http.Request) bool {
return isMimeTypeJSON(r.Header.Get("Content-Type"))
}
func shouldReturnJSON(r *http.Request) bool {
acceptString := strings.ToLower(r.Header.Get("Accept"))
if len(acceptString) == 0 {
return isContentTypeJSON(r)
}
jsonIndex := strings.Index(acceptString, jsonContentType)
xprottpIndex := strings.Index(acceptString, xprottpContentType)
protoIndex := strings.Index(acceptString, protoContentType)
if jsonIndex < 0 && xprottpIndex < 0 && protoIndex < 0 {
return isContentTypeJSON(r)
}
if jsonIndex < 0 {
jsonIndex = 9999
}
if xprottpIndex < 0 {
xprottpIndex = 10000
}
if protoIndex < 0 {
protoIndex = 10001
}
return jsonIndex < xprottpIndex && jsonIndex < protoIndex
}
func wrapMethod(service interface{}, m grpc.MethodDesc, interceptor grpc.UnaryServerInterceptor) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
isJSON := isMimeTypeJSON(r.Header.Get("Content-Type"))
dec := func(i interface{}) (err error) {
defer func() {
if err != nil {
err = NewError(http.StatusBadRequest, &empty.Empty{})
}
}()
if isJSON {
err = unmarshaler.Unmarshal(r.Body, i.(proto.Message))
return
}
var buff []byte
buff, err = ioutil.ReadAll(r.Body)
if err != nil {
return
}
err = proto.Unmarshal(buff, i.(proto.Message))
return
}
resp, err := m.Handler(
//srv interface{},
service,
//ctx context.Context,
r.Context(),
//dec func(interface{}) error,
dec,
//interceptor grpc.UnaryServerInterceptor
interceptor)
statusCode := 0
if err != nil {
handled := false
if statusErr, ok := err.(HTTPStatusError); ok {
handled = true
statusCode = statusErr.HTTPStatusCode()
}
if msgErr, ok := err.(ErrorResponse); ok {
WriteMessage(statusCode, msgErr.Message(), w, r)
handled = true
}
if !handled {
panic(err)
}
return
}
WriteMessage(statusCode, resp.(proto.Message), w, r)
})
}
// WriteMessage is exported to be used for middleware to return proto message
func WriteMessage(statusCode int, msg proto.Message, w http.ResponseWriter, r *http.Request) {
var err error
var isJSON = isMimeTypeJSON(w.Header().Get("Content-Type"))
if w.Header().Get("Content-Type") == "" {
isJSON = shouldReturnJSON(r)
contentType := xprottpContentType
if isJSON {
contentType = jsonContentType
} else if strings.Index(strings.ToLower(r.Header.Get("Accept")), protoContentType) >= 0 {
contentType = protoContentType
}
w.Header().Set("Content-Type", contentType)
}
// start write body
var b []byte
if isJSON {
buf := bytes.NewBuffer(nil)
err = marshaler.Marshal(buf, msg)
if err != nil {
panic(kerrs.Wrapv(err, "marshal message to json error", "response", msg))
}
b = buf.Bytes()
} else {
b, err = proto.Marshal(msg)
if err != nil {
panic(kerrs.Wrapv(err, "marshal message to proto error", "response", msg))
}
}
if statusCode == 0 {
statusCode = http.StatusOK
}
// see "large respone http server not auto send Content-Length" test case
w.Header().Set("Content-Length", strconv.Itoa(len(b)))
w.WriteHeader(statusCode)
w.Write(b)
}