-
Notifications
You must be signed in to change notification settings - Fork 47
/
hello_api.gen.go
440 lines (368 loc) · 11.2 KB
/
hello_api.gen.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
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
// hello-webrpc v1.0.0 77ec2ae70d47ccdbeccf18cded85519e0ad547dd
// --
// Code generated by webrpc-gen with golang generator. DO NOT EDIT.
//
// webrpc-gen -schema=hello-api.ridl -target=golang -pkg=main -server -out=./server/hello_api.gen.go
package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"strings"
"time"
)
// WebRPC description and code-gen version
func WebRPCVersion() string {
return "v1"
}
// Schema version of your RIDL schema
func WebRPCSchemaVersion() string {
return "v1.0.0"
}
// Schema hash generated from your RIDL schema
func WebRPCSchemaHash() string {
return "77ec2ae70d47ccdbeccf18cded85519e0ad547dd"
}
//
// Common types
//
type Kind uint32
const (
Kind_USER Kind = 1
Kind_ADMIN Kind = 2
)
var Kind_name = map[uint32]string{
1: "USER",
2: "ADMIN",
}
var Kind_value = map[string]uint32{
"USER": 1,
"ADMIN": 2,
}
func (x Kind) String() string {
return Kind_name[uint32(x)]
}
func (x Kind) MarshalText() ([]byte, error) {
return []byte(Kind_name[uint32(x)]), nil
}
func (x *Kind) UnmarshalText(b []byte) error {
*x = Kind(Kind_value[string(b)])
return nil
}
func (x *Kind) Is(values ...Kind) bool {
if x == nil {
return false
}
for _, v := range values {
if *x == v {
return true
}
}
return false
}
type User struct {
ID uint64 `json:"id" db:"id"`
Username string `json:"USERNAME" db:"username"`
Role Kind `json:"role"`
Meta map[string]interface{} `json:"meta"`
InternalID uint64 `json:"-"`
CreatedAt *time.Time `json:"created_at,omitempty" db:"created_at"`
}
type Page struct {
Num uint32 `json:"num"`
}
var WebRPCServices = map[string][]string{
"ExampleService": {
"Ping",
"GetUser",
"FindUsers",
},
}
//
// Server types
//
type ExampleService interface {
Ping(ctx context.Context) (bool, error)
GetUser(ctx context.Context, userID uint64) (*User, error)
FindUsers(ctx context.Context, q string) (*Page, []*User, error)
}
//
// Client types
//
type ExampleServiceClient interface {
Ping(ctx context.Context) (bool, error)
GetUser(ctx context.Context, userID uint64) (*User, error)
FindUsers(ctx context.Context, q string) (*Page, []*User, error)
}
//
// Server
//
type WebRPCServer interface {
http.Handler
}
type exampleServiceServer struct {
ExampleService
OnError func(r *http.Request, rpcErr *WebRPCError)
}
func NewExampleServiceServer(svc ExampleService) *exampleServiceServer {
return &exampleServiceServer{
ExampleService: svc,
}
}
func (s *exampleServiceServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
defer func() {
// In case of a panic, serve a HTTP 500 error and then panic.
if rr := recover(); rr != nil {
s.sendErrorJSON(w, r, ErrWebrpcServerPanic.WithCause(fmt.Errorf("%v", rr)))
panic(rr)
}
}()
ctx := r.Context()
ctx = context.WithValue(ctx, HTTPResponseWriterCtxKey, w)
ctx = context.WithValue(ctx, HTTPRequestCtxKey, r)
ctx = context.WithValue(ctx, ServiceNameCtxKey, "ExampleService")
var handler func(ctx context.Context, w http.ResponseWriter, r *http.Request)
switch r.URL.Path {
case "/rpc/ExampleService/Ping":
handler = s.servePingJSON
case "/rpc/ExampleService/GetUser":
handler = s.serveGetUserJSON
case "/rpc/ExampleService/FindUsers":
handler = s.serveFindUsersJSON
default:
err := ErrWebrpcBadRoute.WithCause(fmt.Errorf("no handler for path %q", r.URL.Path))
s.sendErrorJSON(w, r, err)
return
}
if r.Method != "POST" {
w.Header().Add("Allow", "POST") // RFC 9110.
err := ErrWebrpcBadMethod.WithCause(fmt.Errorf("unsupported method %q (only POST is allowed)", r.Method))
s.sendErrorJSON(w, r, err)
return
}
contentType := r.Header.Get("Content-Type")
if i := strings.Index(contentType, ";"); i >= 0 {
contentType = contentType[:i]
}
contentType = strings.TrimSpace(strings.ToLower(contentType))
switch contentType {
case "application/json":
handler(ctx, w, r)
default:
err := ErrWebrpcBadRequest.WithCause(fmt.Errorf("unexpected Content-Type: %q", r.Header.Get("Content-Type")))
s.sendErrorJSON(w, r, err)
}
}
func (s *exampleServiceServer) servePingJSON(ctx context.Context, w http.ResponseWriter, r *http.Request) {
ctx = context.WithValue(ctx, MethodNameCtxKey, "Ping")
// Call service method implementation.
ret0, err := s.ExampleService.Ping(ctx)
if err != nil {
rpcErr, ok := err.(WebRPCError)
if !ok {
rpcErr = ErrWebrpcEndpoint.WithCause(err)
}
s.sendErrorJSON(w, r, rpcErr)
return
}
respPayload := struct {
Ret0 bool `json:"status"`
}{ret0}
respBody, err := json.Marshal(respPayload)
if err != nil {
s.sendErrorJSON(w, r, ErrWebrpcBadResponse.WithCause(fmt.Errorf("failed to marshal json response: %w", err)))
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write(respBody)
}
func (s *exampleServiceServer) serveGetUserJSON(ctx context.Context, w http.ResponseWriter, r *http.Request) {
ctx = context.WithValue(ctx, MethodNameCtxKey, "GetUser")
reqBody, err := io.ReadAll(r.Body)
if err != nil {
s.sendErrorJSON(w, r, ErrWebrpcBadRequest.WithCause(fmt.Errorf("failed to read request data: %w", err)))
return
}
defer r.Body.Close()
reqPayload := struct {
Arg0 uint64 `json:"userID"`
}{}
if err := json.Unmarshal(reqBody, &reqPayload); err != nil {
s.sendErrorJSON(w, r, ErrWebrpcBadRequest.WithCause(fmt.Errorf("failed to unmarshal request data: %w", err)))
return
}
// Call service method implementation.
ret0, err := s.ExampleService.GetUser(ctx, reqPayload.Arg0)
if err != nil {
rpcErr, ok := err.(WebRPCError)
if !ok {
rpcErr = ErrWebrpcEndpoint.WithCause(err)
}
s.sendErrorJSON(w, r, rpcErr)
return
}
respPayload := struct {
Ret0 *User `json:"user"`
}{ret0}
respBody, err := json.Marshal(respPayload)
if err != nil {
s.sendErrorJSON(w, r, ErrWebrpcBadResponse.WithCause(fmt.Errorf("failed to marshal json response: %w", err)))
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write(respBody)
}
func (s *exampleServiceServer) serveFindUsersJSON(ctx context.Context, w http.ResponseWriter, r *http.Request) {
ctx = context.WithValue(ctx, MethodNameCtxKey, "FindUsers")
reqBody, err := io.ReadAll(r.Body)
if err != nil {
s.sendErrorJSON(w, r, ErrWebrpcBadRequest.WithCause(fmt.Errorf("failed to read request data: %w", err)))
return
}
defer r.Body.Close()
reqPayload := struct {
Arg0 string `json:"q"`
}{}
if err := json.Unmarshal(reqBody, &reqPayload); err != nil {
s.sendErrorJSON(w, r, ErrWebrpcBadRequest.WithCause(fmt.Errorf("failed to unmarshal request data: %w", err)))
return
}
// Call service method implementation.
ret0, ret1, err := s.ExampleService.FindUsers(ctx, reqPayload.Arg0)
if err != nil {
rpcErr, ok := err.(WebRPCError)
if !ok {
rpcErr = ErrWebrpcEndpoint.WithCause(err)
}
s.sendErrorJSON(w, r, rpcErr)
return
}
respPayload := struct {
Ret0 *Page `json:"page"`
Ret1 []*User `json:"users"`
}{ret0, ret1}
respBody, err := json.Marshal(respPayload)
if err != nil {
s.sendErrorJSON(w, r, ErrWebrpcBadResponse.WithCause(fmt.Errorf("failed to marshal json response: %w", err)))
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write(respBody)
}
func (s *exampleServiceServer) sendErrorJSON(w http.ResponseWriter, r *http.Request, rpcErr WebRPCError) {
if s.OnError != nil {
s.OnError(r, &rpcErr)
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(rpcErr.HTTPStatus)
respBody, _ := json.Marshal(rpcErr)
w.Write(respBody)
}
func RespondWithError(w http.ResponseWriter, err error) {
rpcErr, ok := err.(WebRPCError)
if !ok {
rpcErr = ErrWebrpcEndpoint.WithCause(err)
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(rpcErr.HTTPStatus)
respBody, _ := json.Marshal(rpcErr)
w.Write(respBody)
}
//
// Helpers
//
type contextKey struct {
name string
}
func (k *contextKey) String() string {
return "webrpc context value " + k.name
}
var (
HTTPResponseWriterCtxKey = &contextKey{"HTTPResponseWriter"}
HTTPRequestCtxKey = &contextKey{"HTTPRequest"}
ServiceNameCtxKey = &contextKey{"ServiceName"}
MethodNameCtxKey = &contextKey{"MethodName"}
)
func ServiceNameFromContext(ctx context.Context) string {
service, _ := ctx.Value(ServiceNameCtxKey).(string)
return service
}
func MethodNameFromContext(ctx context.Context) string {
method, _ := ctx.Value(MethodNameCtxKey).(string)
return method
}
func RequestFromContext(ctx context.Context) *http.Request {
r, _ := ctx.Value(HTTPRequestCtxKey).(*http.Request)
return r
}
func ResponseWriterFromContext(ctx context.Context) http.ResponseWriter {
w, _ := ctx.Value(HTTPResponseWriterCtxKey).(http.ResponseWriter)
return w
}
//
// Errors
//
type WebRPCError struct {
Name string `json:"error"`
Code int `json:"code"`
Message string `json:"msg"`
Cause string `json:"cause,omitempty"`
HTTPStatus int `json:"status"`
cause error
}
var _ error = WebRPCError{}
func (e WebRPCError) Error() string {
if e.cause != nil {
return fmt.Sprintf("%s %d: %s: %v", e.Name, e.Code, e.Message, e.cause)
}
return fmt.Sprintf("%s %d: %s", e.Name, e.Code, e.Message)
}
func (e WebRPCError) Is(target error) bool {
if target == nil {
return false
}
if rpcErr, ok := target.(WebRPCError); ok {
return rpcErr.Code == e.Code
}
return errors.Is(e.cause, target)
}
func (e WebRPCError) Unwrap() error {
return e.cause
}
func (e WebRPCError) WithCause(cause error) WebRPCError {
err := e
err.cause = cause
err.Cause = cause.Error()
return err
}
func (e WebRPCError) WithCausef(format string, args ...interface{}) WebRPCError {
cause := fmt.Errorf(format, args...)
err := e
err.cause = cause
err.Cause = cause.Error()
return err
}
// Deprecated: Use .WithCause() method on WebRPCError.
func ErrorWithCause(rpcErr WebRPCError, cause error) WebRPCError {
return rpcErr.WithCause(cause)
}
// Webrpc errors
var (
ErrWebrpcEndpoint = WebRPCError{Code: 0, Name: "WebrpcEndpoint", Message: "endpoint error", HTTPStatus: 400}
ErrWebrpcRequestFailed = WebRPCError{Code: -1, Name: "WebrpcRequestFailed", Message: "request failed", HTTPStatus: 400}
ErrWebrpcBadRoute = WebRPCError{Code: -2, Name: "WebrpcBadRoute", Message: "bad route", HTTPStatus: 404}
ErrWebrpcBadMethod = WebRPCError{Code: -3, Name: "WebrpcBadMethod", Message: "bad method", HTTPStatus: 405}
ErrWebrpcBadRequest = WebRPCError{Code: -4, Name: "WebrpcBadRequest", Message: "bad request", HTTPStatus: 400}
ErrWebrpcBadResponse = WebRPCError{Code: -5, Name: "WebrpcBadResponse", Message: "bad response", HTTPStatus: 500}
ErrWebrpcServerPanic = WebRPCError{Code: -6, Name: "WebrpcServerPanic", Message: "server panic", HTTPStatus: 500}
ErrWebrpcInternalError = WebRPCError{Code: -7, Name: "WebrpcInternalError", Message: "internal error", HTTPStatus: 500}
ErrWebrpcClientDisconnected = WebRPCError{Code: -8, Name: "WebrpcClientDisconnected", Message: "client disconnected", HTTPStatus: 400}
ErrWebrpcStreamLost = WebRPCError{Code: -9, Name: "WebrpcStreamLost", Message: "stream lost", HTTPStatus: 400}
ErrWebrpcStreamFinished = WebRPCError{Code: -10, Name: "WebrpcStreamFinished", Message: "stream finished", HTTPStatus: 200}
)