forked from webrpc/gen-golang
-
Notifications
You must be signed in to change notification settings - Fork 0
/
helpers.go.tmpl
291 lines (240 loc) · 8.47 KB
/
helpers.go.tmpl
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
{{define "helpers"}}
//
// Helpers
//
type ErrorPayload struct {
Status int `json:"status"`
Code string `json:"code"`
Cause string `json:"cause,omitempty"`
Msg string `json:"msg"`
Error string `json:"error"`
}
type Error interface {
// Code is of the valid error codes
Code() ErrorCode
// Msg returns a human-readable, unstructured messages describing the error
Msg() string
// Cause is reason for the error
Cause() error
// Error returns a string of the form "webrpc error <Code>: <Msg>"
Error() string
// Error response payload
Payload() ErrorPayload
}
func Errorf(code ErrorCode, msgf string, args ...interface{}) Error {
msg := fmt.Sprintf(msgf, args...)
if IsValidErrorCode(code) {
return &rpcErr{code: code, msg: msg}
}
return &rpcErr{code: ErrInternal, msg: "invalid error type " + string(code)}
}
func WrapError(code ErrorCode, cause error, format string, args ...interface{}) Error {
msg := fmt.Sprintf(format, args...)
if IsValidErrorCode(code) {
return &rpcErr{code: code, msg: msg, cause: cause}
}
return &rpcErr{code: ErrInternal, msg: "invalid error type " + string(code), cause: cause}
}
func Failf(format string, args ...interface{}) Error {
return Errorf(ErrFail, format, args...)
}
func WrapFailf(cause error, format string, args ...interface{}) Error {
return WrapError(ErrFail, cause, format, args...)
}
func ErrorNotFound(format string, args ...interface{}) Error {
return Errorf(ErrNotFound, format, args...)
}
func ErrorInvalidArgument(argument string, validationMsg string) Error {
return Errorf(ErrInvalidArgument, argument+" "+validationMsg)
}
func ErrorRequiredArgument(argument string) Error {
return ErrorInvalidArgument(argument, "is required")
}
func ErrorInternal(format string, args ...interface{}) Error {
return Errorf(ErrInternal, format, args...)
}
type ErrorCode string
const (
// Unknown error. For example when handling errors raised by APIs that do not
// return enough error information.
ErrUnknown ErrorCode = "unknown"
// Fail error. General failure error type.
ErrFail ErrorCode = "fail"
// Canceled indicates the operation was cancelled (typically by the caller).
ErrCanceled ErrorCode = "canceled"
// InvalidArgument indicates client specified an invalid argument. It
// indicates arguments that are problematic regardless of the state of the
// system (i.e. a malformed file name, required argument, number out of range,
// etc.).
ErrInvalidArgument ErrorCode = "invalid argument"
// DeadlineExceeded means operation expired before completion. For operations
// that change the state of the system, this error may be returned even if the
// operation has completed successfully (timeout).
ErrDeadlineExceeded ErrorCode = "deadline exceeded"
// NotFound means some requested entity was not found.
ErrNotFound ErrorCode = "not found"
// BadRoute means that the requested URL path wasn't routable to a webrpc
// service and method. This is returned by the generated server, and usually
// shouldn't be returned by applications. Instead, applications should use
// NotFound or Unimplemented.
ErrBadRoute ErrorCode = "bad route"
// AlreadyExists means an attempt to create an entity failed because one
// already exists.
ErrAlreadyExists ErrorCode = "already exists"
// PermissionDenied indicates the caller does not have permission to execute
// the specified operation. It must not be used if the caller cannot be
// identified (Unauthenticated).
ErrPermissionDenied ErrorCode = "permission denied"
// Unauthenticated indicates the request does not have valid authentication
// credentials for the operation.
ErrUnauthenticated ErrorCode = "unauthenticated"
// ResourceExhausted indicates some resource has been exhausted, perhaps a
// per-user quota, or perhaps the entire file system is out of space.
ErrResourceExhausted ErrorCode = "resource exhausted"
// FailedPrecondition indicates operation was rejected because the system is
// not in a state required for the operation's execution. For example, doing
// an rmdir operation on a directory that is non-empty, or on a non-directory
// object, or when having conflicting read-modify-write on the same resource.
ErrFailedPrecondition ErrorCode = "failed precondition"
// Aborted indicates the operation was aborted, typically due to a concurrency
// issue like sequencer check failures, transaction aborts, etc.
ErrAborted ErrorCode = "aborted"
// OutOfRange means operation was attempted past the valid range. For example,
// seeking or reading past end of a paginated collection.
//
// Unlike InvalidArgument, this error indicates a problem that may be fixed if
// the system state changes (i.e. adding more items to the collection).
//
// There is a fair bit of overlap between FailedPrecondition and OutOfRange.
// We recommend using OutOfRange (the more specific error) when it applies so
// that callers who are iterating through a space can easily look for an
// OutOfRange error to detect when they are done.
ErrOutOfRange ErrorCode = "out of range"
// Unimplemented indicates operation is not implemented or not
// supported/enabled in this service.
ErrUnimplemented ErrorCode = "unimplemented"
// Internal errors. When some invariants expected by the underlying system
// have been broken. In other words, something bad happened in the library or
// backend service. Do not confuse with HTTP Internal Server Error; an
// Internal error could also happen on the client code, i.e. when parsing a
// server response.
ErrInternal ErrorCode = "internal"
// Unavailable indicates the service is currently unavailable. This is a most
// likely a transient condition and may be corrected by retrying with a
// backoff.
ErrUnavailable ErrorCode = "unavailable"
// DataLoss indicates unrecoverable data loss or corruption.
ErrDataLoss ErrorCode = "data loss"
// ErrNone is the zero-value, is considered an empty error and should not be
// used.
ErrNone ErrorCode = ""
)
func HTTPStatusFromErrorCode(code ErrorCode) int {
switch code {
case ErrCanceled:
return 408 // RequestTimeout
case ErrUnknown:
return 400 // Bad Request
case ErrFail:
return 422 // Unprocessable Entity
case ErrInvalidArgument:
return 400 // BadRequest
case ErrDeadlineExceeded:
return 408 // RequestTimeout
case ErrNotFound:
return 404 // Not Found
case ErrBadRoute:
return 404 // Not Found
case ErrAlreadyExists:
return 409 // Conflict
case ErrPermissionDenied:
return 403 // Forbidden
case ErrUnauthenticated:
return 401 // Unauthorized
case ErrResourceExhausted:
return 403 // Forbidden
case ErrFailedPrecondition:
return 412 // Precondition Failed
case ErrAborted:
return 409 // Conflict
case ErrOutOfRange:
return 400 // Bad Request
case ErrUnimplemented:
return 501 // Not Implemented
case ErrInternal:
return 500 // Internal Server Error
case ErrUnavailable:
return 503 // Service Unavailable
case ErrDataLoss:
return 500 // Internal Server Error
case ErrNone:
return 200 // OK
default:
return 0 // Invalid!
}
}
func IsErrorCode(err error, code ErrorCode) bool {
if rpcErr, ok := err.(Error); ok {
if rpcErr.Code() == code {
return true
}
}
return false
}
func IsValidErrorCode(code ErrorCode) bool {
return HTTPStatusFromErrorCode(code) != 0
}
type rpcErr struct {
code ErrorCode
msg string
cause error
}
func (e *rpcErr) Code() ErrorCode {
return e.code
}
func (e *rpcErr) Msg() string {
return e.msg
}
func (e *rpcErr) Cause() error {
return e.cause
}
func (e *rpcErr) Error() string {
if e.cause != nil && e.cause.Error() != "" {
if e.msg != "" {
return fmt.Sprintf("webrpc %s error: %s -- %s", e.code, e.cause.Error(), e.msg)
} else {
return fmt.Sprintf("webrpc %s error: %s", e.code, e.cause.Error())
}
} else {
return fmt.Sprintf("webrpc %s error: %s", e.code, e.msg)
}
}
func (e *rpcErr) Payload() ErrorPayload {
statusCode := HTTPStatusFromErrorCode(e.Code())
errPayload := ErrorPayload{
Status: statusCode,
Code: string(e.Code()),
Msg: e.Msg(),
Error: e.Error(),
}
if e.Cause() != nil {
errPayload.Cause = e.Cause().Error()
}
return errPayload
}
type contextKey struct {
name string
}
func (k *contextKey) String() string {
return "webrpc context value " + k.name
}
var (
// For Client
HTTPClientRequestHeadersCtxKey = &contextKey{"HTTPClientRequestHeaders"}
// For Server
HTTPResponseWriterCtxKey = &contextKey{"HTTPResponseWriter"}
HTTPRequestCtxKey = &contextKey{"HTTPRequest"}
ServiceNameCtxKey = &contextKey{"ServiceName"}
MethodNameCtxKey = &contextKey{"MethodName"}
)
{{- end }}